NSMutabledictionary not working
I am new to Iphone programming. Please correct me where am I going wrong.
I have two viewcontrollers
viewcontroller1 viewcontroller2
In viewcontroller1,
-(IBAction) getQuestions:(id)sender
{
NSLog(@"In get questions..");
[[self viewcontroller2] initWithData:userInfo];
[self presentModalViewController:viewcontroller2 animated:YES];
[quesions autorelease];
}
In viewController2 I have the following code.
-(id)initWithData:(NSMutableDictionary*)data
{
self = [super init];
if(self)
{
userInfo = [[NS开发者_如何转开发MutableDictionary alloc] initWithDictionary:data];
}
return self;
}
-(IBAction) getQuesionAfterPopUp:(id) sender
{
NSLog(@"In get question..After popup...%@",userInfo);
}
For some reason "userInfo" is null. Why is it null even after using init with data.
You didn't initialize correctly, therefore the instance variable userInfo
is not accessible.
Initialization should look like this:
- (id)initWithData:(NSMutableDictionary *)data
{
self = [super init]; // 'self' and it's instance variables are accessible at this point ...
if (self)
{
userInfo = // etc...
}
return self;
}
You might want to read up on this link for more information on how to implement designated initializers. Especially focus on the topic Implementing an Initializer.
in the above code you don't retain your userInfo
object. Try
userInfo = [[[NSMutableDictionary alloc] initWithDictionary:data]]retain];
Or if userInfo is a property like:
@property (nonatomic, retain)
Try:
self.userInfo = [[NSMutableDictionary alloc] initWithDictionary:data]];
Which will automatically retain the userInfo. Please note by not calling self you are assigning straight to the instance variable.
Finally, make sure that the data
object is not empty
精彩评论