1

How to create reusable classes in objective C? What should I do? What should I not do?

Please explain with some code.

I dont want to know how to creating subclass from the apple classes .

I want to know if I write the own class for one project then how should I make those class as more reusable for another project.

for that What should I do? What should I not do?

or what should I consider while writing the class for the first project?

SMR
  • 6,628
  • 2
  • 35
  • 56
rithik
  • 778
  • 1
  • 9
  • 21
  • Google revealed this: http://www.devbypractice.com/reusable-singleton-class-in-objective-c-for-iphone-and-ipad/ – Pripyat Mar 14 '11 at 13:13
  • @David: This is only a Singleton class, which may be what he wants, but the OP did not specifically mention that pattern. – FreeAsInBeer Mar 14 '11 at 13:19

1 Answers1

6

To add an Obj-C class to your project, simply right click the Classes folder and choose 'Add' -> 'New File'. Choose 'Objective-C Class' and make sure the 'Subclass of' dropdown is set to 'NSObject'. Press 'Next', name your class and check the checkbox for 'Make .h file as well'. Now you should have a .h and .m file in your project. You use these the same way you would with a view controller or view. For example:

.h file:

@interface MyObject : NSObject {
}
-(void)myTestMethod:(NSString*)name
@end

.m file:

@implementation MyObject
-(void)myTestMethod:(NSString*)name {
    NSLog(@"Hello, %@!", name);
}
@end

Then to use this object, you would instantiate it like so:

MyObject *myObj = [[MyObject alloc] init];

And use methods like so:

[myObj myTestMethod:@"rithik"];

And release it once you are done:

[myObj release];

Edit: I've read your modified question, and I now understand it to be: "How can I write reusable code?" This is going to be very similar between languages. Patterns have been developed that can be implemented in most languages and best practices are frequently portable to another platform. Here are some personal tips:

  • Use delegates and interfaces
  • Use unique class names that won't clash with existing classes from Apple or other frameworks.
  • Use private headers to prevent others from accessing methods they don't need.

And here are some links that should help steer you in the right direction:

Community
  • 1
  • 1
FreeAsInBeer
  • 12,937
  • 5
  • 50
  • 82