i have a MyObject. when my program runs, i create a new MyObject
self.myObject = [[MyObject alloc] initWithStuff:stuff];
later in my code, i need to create a new MyObject.
my question is, do i need to create a new MyObject with an “init” method?
.h
#import <UIKit/UIKit.h>
@interface MyObject : NSObject
{}
-(id)initWithStuff:(NSString *)stuff;
-(id)initWithNewStuff:(NSString *)newStuff;
-(id)newObjectWithStuff:(NSString *)newStuff;
@end
.m
-(id)initWithStuff:(NSString *)stuff;
{
if (self = [super init])
{
self.myStuff = stuff;
}
return self;
}
-(id)initWithNewStuff:(NSString *)newStuff;{
if (self = [super init])
{
self.myStuff = newStuff;
}
return self;
}
-(id)newObjectWithStuff:(NSString *)newStuff;
{
self.myStuff = newStuff;
return self;
}
or can i use a non-init method to create it?
in my code:
self.myObject = [[MyObject alloc] initWithNewStuff:newStuff];
or
self.myObject = [self.myObject newObjectWithStuff:newStuff];
i guess my question boils down to: what does
if (self = [super init])
do?
working with other objects such as dictionaries, i know “NSDictionary *myDict = myOtherDict” is perfect valid.
You can name your custom initializers as you want, but there’s a convention to start your initializer method with “init”.
In examples you wrote, the objects are a subclass of
NSObjectthe the root class of all hierarchies. The keywordsuperrefers to the class above in the hierarchy (your class’s superclass), so basically, you’re calling theinitmethod ofNSObjectwhich creates and initializes an object right after memory has been allocated for it (that’s whatallocmethod does). Then, you check if the method returned an object and initialize your own properties.Take a look at this guide and make sure you understand everything what is in there https://developer.apple.com/library/mac/#documentation/cocoa/conceptual/objectivec/introduction/introobjectivec.html .