Initialization methods - objective-c

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 NSObject the the root class of all hierarchies. The keyword super refers to the class above in the hierarchy (your class's superclass), so basically, you're calling the init method of NSObject which creates and initializes an object right after memory has been allocated for it (that's what alloc method 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 .

When you are calling
self.myObject = [self.myObject newObjectWithStuff:newStuff];
you just making reference on an existing memory location. If you really want a new object You should call like
self.myObject = [[MyObject alloc] initWithNewStuff:newStuff];
The alloc key word allocates memory for a variable

Related

Overriding init method to allocate memory for instance variable object

I am attempting to override the init method of a class so that initializing the object also initializes the ivar object:
-(id)init
{
if (self = [super init])
{
someIVarObject = [SomeClass alloc] init];
}
return self;
}
1) Would this code even work, and even so, is this solution discouraged?
2) Why is the if condition not == ? Is it an assignment? If so, why the if?
Sorry if this is obvious! >_<
Yes, it would work, and afaik it's still the way it should be done.
What it does is to call [super init] and allows it to do one of three things;
Return self (ie the same object self is already set to.
Return an entirely new object.
Return nil for failure.
The result is then assigned to self, which makes sure that the rest of the constructor operates on the correct object in case it changed. The if is there to catch the case where [super init] returned nil, in which case the rest of the constructor should be skipped.
1) Here you are declaring a local variable someIVarObject. You should have declared this within the interface or implementation of your class in curly braces, and should then assign it as someIvarObject = .... An example:
#implementation MyClass {
SomeClass *someIvarObject;
}
- (id)init
{
if(self = [super init])
{
someIvarObject = [[SomeClass alloc] init];
}
return self;
}
#end
2) It is an assignment. There is a long history behind this idiom but it mostly comes down to handling the possibility that [super init] returns a different object than init was originally invoked upon.
This...
if(self = [super init])
will work, but it will give you a compiler warning (unless you've turned off this warning).
You can also suppress the warning by using double parenthesis:
if((self = [super init]))
My current preference:
self = [super init];
if(self)
You've got some typos, unbalanced brackets, and the thing you say is an ivar is not an ivar (you declare it inside the if, which makes its scope local to that block. You want to put instance variables in the {}s after your #implementation or #interface declarations). But yes, this is generally how this would work.
However, I'd take a hard look at whether you really need an ivar or not. I can't remember the last time I used one in my code. 99% of the situations I used to use them in, a #property is now a much better solution.
As an added benefit, #propertys synthesize their own getters and setters, (usually) obviating the need to write manual allocing boilerplate, thus making this question moot.
1) this code will work but this line:
SomeClass *someIVarObject = [SomeClass alloc] init];
makes a little sense. Declare SomeClass *someIVarObject in .h file and initialize it in init like this:
someIVarObject = [SomeClass alloc] init];
2) this line if (self = [super init]) is equivalent to:
self = [super init]; if (self != nil)
i.e. it ensures that init method of the base class has returned a proper value

Objective-c - what does [super init] return?

New to objective-c. Wrote a code-snippet to better understand the init mechanism, and ended up with a few questions.
#implementation MyClass
-(id) init
{
if (self) {
i = 5;
NSLog(#"self before init - %# %p i=%d",[self className], &self, i);
} else {
NSLog(#"self is null???");
}
id someClass = [super init];
NSLog(#"the result of super-init - %# %p",[someClass className], &someClass);
self = [super init];
if (self) {
NSLog(#"self after init - %# %p %d",[self className], &self, i);
} else {
NSLog(#"self is null???");
}
return self;
}
i is a private instance variable int.
Here is the result:
2012-12-14 18:01:26.403 Init[1621:303] self before init - MyClass 0x7fff5fbff848 i=5
2012-12-14 18:01:26.405 Init[1621:303] the result of super-init - MyClass 0x7fff5fbff838
2012-12-14 18:01:26.405 Init[1621:303] self after init - MyClass 0x7fff5fbff848 5
What really surprised me is that that someClass's class Name is MyClass.
How does NSObject know to return the sub-classes instance (not just the type match, it is the exact same object)?
I'm aware that it is not good form to call init many times, and initialize instance variables before calling init but I was just experimenting.
Thanks.
You do need to use the standard schemen (more or less):
-(id)init {
self = [super init];
if (self) {
// Do initialization stuff
}
}
Your class subclasses some other class. The call to super init runs the init routine of your superclass. Without it your class is not properly initialized and may malfunction strangely. (However, it's probably not wise to call super init twice, as this could have bad side-effects.)
There are cases where you would not call super init, but would instead call a version of init in your own class. Basically, if you have initWithJunk: and init, you can have initWithJunk: call [self init] instead of [super init] so that the stuff that self init would do gets done and doesn't have to be reproduced in initWithJunk:.
This is especially critical if you write a "category" that adds an init... method to an existing class -- you must call some version of [self init] to assure that the base class's initializer runs.
Understand that the super init method is not (usually) replacing the existing instance with a new one, but rather is initializing instance fields in it that belong to the superclass. The reason for receiving the "self" value back from the super init call is two-fold:
The init routine can return a nil in the event that some sort of error occurs.
In some (rare) special cases the init routine may replace the supplied instance with a different one (eg, a cached version).

How to initialize a NSMutableArray in Objective C?

I come from a Java background and I am learning Objective C. I am trying to create a class that has a string array and a member function to modify the Array. My code looked like this:
#implementation TAWChapter
#synthesize mSubject;
#synthesize mItems;
- (id) init{
self.mItems = [[NSMutableArray alloc] init];
return self;
}
- (void) setSubject:(NSString *)subject{
self.mSubject = subject;
}
- (void) addItem:(NSString *)item{
[self.mItems addObject:#"asdf"];
}
#end
Which didn't work. I got a "[__NSArrayI addObject:]: unrecognized selector sent to instance " and a "NSInvalidArgumentException". After searching on internet, I changed the single line in the constructor to:
self.mItems = [self.mItems init];
It worked, but why? From a Java developer's point of view the first one makes more sense than the second one. And I have another line it's the same as the first one but it's working(not in a constructor). Can someone explain this to me please?
First of all, you should adhere to Objective-C coding conventions. In Objective-C, classes don't have constructors, they have initialisers. In Objective-C, initialisers invoke the initialiser of the superclass, so it should look like this:
- init
{
self = [super init];
if (!self) return nil;
// set up other stuff here
return self;
}
Second, unless you are using ARC, you might have a memory leak. The first line of your initialiser assigns an object that you own to a property that also likely takes ownership. You should use either:
// property takes care of ownership
self.mItems = [NSMutableArray array];
or:
// assign to instance variable directly with owned object
mItems = [[NSMutableArray alloc] init];
Apple sometimes discourage the use of accessor methods in initialisers because it can fiddle with things like KVO, but consistent use of accessor methods ensures proper object ownership and memory management.
By changing your line in your initialiser to:
self.mItems = [self.mItems init];
does nothing. When your initialiser method is called (which is typically just after it has been allocated), all instance variables are automatically set to nil. So what you are doing is just:
self.mItems = [nil init];
which is just:
self.mItems = nil;
and, don't use init without first allocating an instance, and never use init more than once.
If you do not let the superclass initialise itself, then it may manifest as problems in other areas. Do a Build & Analyze and ensure you have fixed up any issues pointed out by the analyser.
Since objective-c is a superset of c, it's basically c with some "OO" syntax sugar. Before you can create (or use!) an object, you must alloc space for it in the heap. you do this with [Class alloc]. The next step is the initialization of that space. alloc returns a pointer to that space in the heap, which you initialize with init ;)
So you call Class *myObjc = [[Class alloc] init];.
If you use inheritance (which you do since you inherit from NSOBject), you must make sure that your superclass initialized everything properly, thats the call to super. To make sure you don't get a runtime error, check for self != nil, which you do implicitly with if(self)
self.mItems = [self.mItems init]; // doesn't do anything, since you call the getter for mItems with self.mItems and try to init. then you try to set mItmes to itself.
use this code:
#implementation TAWChapter
#synthesize mSubject, mItems;
- (id)init
{
self = [super init];
if (self) {
mItems = [[NSMutableArray alloc] init];
}
return self;
}
- (void) setSubject:(NSString *)subject{
mSubject = subject;
}
- (void) addItem:(NSString *)item{
[mItems addObject:item];
}
#end
You should call super and assign its result to self in your init method:
- (id)init
{
self = [super init];
if (self) {
self.mItems = [[NSMutableArray alloc] init];
}
return self;
}
The another way could be creating NSMutableArray from NSArray:
NSMutableArray *myMutableArray = [NSMutableArray arrayWithArray:myArray];

Objective-C, class identity

I have the following situation, i can't resolve:
#interface Deck : NSObject
#interface MasterDeck : Deck
#interface PlayerDeck : Deck
Inside MasterDeck class, as part of initialization, i call
[self cutDeckImageIntoCards]; // We don't get to execute this method
Call results in an error [PlayerDeck cutDeckImageIntoCards]: unrecognized selector sent to instance
Indeed, PlayerDeck does not have this method .. but why is it being called at all?
After looking at MasterDeck's initialization i added a few debugging statements:
static MasterDeck *gInstance = NULL;
+(MasterDeck *) instance {
#synchronized(self) {
if (gInstance == NULL) {
gInstance = [[self alloc] init];
}
}
return gInstance;
}
-(id) init {
if (gInstance != NULL) {
return gInstance;
}
// MasterDeck
self = [super init];
// PlayerDeck
if (self) {
// Lots of stuff
[self cutDeckImageIntoCards]
// Some more stuff
}
gInstance = self;
return gInstance;
}
Ok, so MasterDeck is PlayerDeck because' Deck thinks it is a PlayerDeck ... Deck confirms
Deck is created as follows:
static Deck *gInstance = NULL;
+(Deck *) instance {
#synchronized(self) {
if (gInstance == NULL) {
gInstance = [[self alloc] init];
}
}
return gInstance;
}
-(id) init {
if (gInstance != NULL) {
return gInstance;
}
self = [super init];
if (self) {
// Do something
}
NSLog(#"Deck thinks it's a %#", [[self class ]description]); // PlayerDeck
gInstance = self;
return gInstance;
}
So, again
#interface Deck : NSObject
Assuming above Singleton Implementation, why would Deck think it's actually a PlayerDeck?
So the way you've written this, if you create the PlayDeck instance first, then the Deck instance is now a PlayDeck.
And then if you go to create the MasterDeck instance, your call to [super init] dutifully returns that previous PlayDeck instance.
So why is Deck a singleton at all? Deck has two subclasses that are singletons, but are you really looking for a singleton Deck also?
At a minimum, you can make this sort of work by not setting gInstance from within each init. Let the class method do that. Just return self from each of the init's. Also, remove the check for gInstance being not null, other Deck's init will always return Deck's instance once you have an instance of Deck.
But beyond that, I would rethink this idea a bit. Hope that helps.
You'll probably want to separate your singleton class from the actual class.
Try implementing it as in this example,
+(id) instance {
static dispatch_once_t pred;
static MasterDeck *sharedInstance = nil;
dispatch_once(&pred, ^{
sharedInstance = [[MasterDeck alloc] init];
});
return sharedInstance;
}
What happens if you replace [[self alloc] init] with [[MasterDeck alloc] init]?
It may be that somehow self is PlayerDeck. To make sure, you could NSLog([self description]) just before calling + alloc.
Edit
I assume that the interesting part of the code you have above is part of the #implementation of MasterDeck. My suggestion would be to try a lot more logging, including determining what super and [self class] are before calling [super init], although these may be misleading...
Also, as a side note, I believe that you should call [self release] in init if you are returning the previously-created instance.
What does the [super init] method look like? Can you step into it, or is it the default initializer?
Edit 2
I think you're doing singletons wrong. If you initialize a PlayerDeck, that would create a singleton in Deck which is an instance of PlayerDeck. Then later, when you initialize a MasterDeck, calling [super init] will return the instance already created by the PlayerDeck.
It looks like you try to be clever, but fact is - often the computer is even smarter. :)
Your deck class caches an instance in gInstance - in fact, it looks like it may store a Deck, a PlayerDeck, or a MasterDeck, depending on what and how you call / instantiate first. After that, this very instance is returned by that init method.
I strongly suggest to get this code clean and readable. I bet there are numerous problems with this code - but your problem is already a good example. Your logic (which should be simple, I guess) can surely be implemented much easier.
Note - I'm not against singletons, but this sort of code stacking is an absolute no-go. It's hard to get more dependency logic into those lines. ;)

Objective C init

Disclaimer, I'm new to Objective C. But I can't find this explained. I've seen two ways of implementing init:
- (id)init {
if ([super init]) {
return self;
} else {
return nil;
}
}
and
- (id)init {
if (self = [super init]) {
// do your init business here
}
return self;
}
so let's say i have:
myObj = [[MyObject alloc] init];
where MyObject class is a subclass of NSObject. in the second example, does init not return an initialized version of NSObject? so myObj would ... how would it know what it is? wouldn't it think it was an NSObject rather than a MyObject?
1) First version is just wrong. self should be always assigned with value returned by super initializer, because init<...> of super can return another object upon initialization (it's not unusual BTW). Second version is actually an 'official' way to implement init<...> methods.
2) 'wouldn't it think it was an NSObject rather than a MyObject'. myObj is instance of 'NSObject' and instance of 'MyObject'. It's the whole point of inheritance.
i just want to know, under the hood, how it does it.
It's pretty simple. 99.9% of all the classes you'll ever write will inherit from NSObject in some fashion. In the initializers, you're supposed to invoke super's designated initializer and assign it to self. Eventually, [super init] will be invoking -[NSObject init]. According to the documentation, that's implemented like this:
- (id)init {
return self;
}
So technically, if you inherit directly from NSObject, you're probably safe to not do the assignation of self = [super init];, because you know (and you're guaranteed) that this is equivalent to: self = self;, which is kind of pointless. Regardless, you should leave it in for consistency's sake.
However, once you start getting further down the inheritance chain, and especially when you're inheriting from opaque classes (ie, a class whose .m file you do not have), then things start getting shady. It is possible that you'll come across a class whose designated initializer looks something like this:
- (id) initWithFoo:(id)aFoo {
if ([aFoo isSuperFast]) {
[self release];
return [[SuperFastFooWrapper alloc] initWithFoo:aFoo];
}
self = [super init];
if (self) {
_foo = [aFoo retain];
}
}
This isn't as common, but it does happen. In this case, we're destroying self ([self release], to balance the alloc call that immediately preceded this) and instead returning a different object.