keyboarddrummer
keyboarddrummer

Reputation: 156

Objective C Object Not Updating

I am using ARC, XCode 4.2, OS X 10.6, and building for the iPad 5.0 Simulator (each object is displayed in a table view cell).


I have an NSArray of objects that have the following properties:

// Relevant ModelClass.h
@property (strong, nonatomic) ChildObject* childObject;
@property Boolean type1;
@property Boolean type2;

// Relevant ChildObject.h
@property (strong, nonatomic) NSString* name; 

I am trying to ensure that each instance of ChildObject (always a property of the ModelObject) has a name set for display. I am using the following code to accomplish this:

// Called after the objects are all loaded into the objects NSArray
// _data is an NSMutableArray that is allocated and initialized
// Loop through the model array and make sure that everyone has a name set
for (ModelClass *model in objects) {
    NSLog(@"B %@", [[model childObject] name]);
    if (model.num == 0) {
        if (model.type1) {
            [model.childObject setName: @"type1"];
            NSLog(@"Updated Name: %@", model.childObject.name);
        }
        else {
            model.childObject.name = @"type2";
        }
    }

    if (! model.childObject.name) {
        [model.childObject setName:@"?"];
    }
    [_data addObject:model];

    NSLog(@"E %@", [[model childObject] name]);
}

The objects array has two objects: one with a name, and one without (and the boolean value for type1 set to true).

However, when the code executes, the log looks like this:

// Log Output
2012-07-18 10:40:27.760 AppName[13462:40b] B A Really Long Name    
2012-07-18 10:40:27.760 AppName[13462:40b] E A Really Long Name
2012-07-18 10:40:27.760 AppName[13462:40b] B (null)
2012-07-18 10:40:27.761 AppName[13462:40b] Updated Name: (null)
2012-07-18 10:40:27.761 AppName[13462:40b] E (null)

The first three lines are correct (first object's name not changed, second object with name set to null). For some reason, the name of the second object is not updated, even though it appears that the code is executing to change its name.

Why doesn't the object's name update? I am new to Objective-C, so it may be something really simple.

Upvotes: 2

Views: 223

Answers (1)

TeaCupApp
TeaCupApp

Reputation: 11452

Remember, doing

@property (strong, nonatomic) ChildObject* childObject;

and

@synthesize childObject = _childObject 

compiler will not give your variable a memory. You must alloc and init your childObject in order to use it, or setName of their variable. You need something like,

_childObject = [[ChildObject alloc] init];

and then,

[_childObject setName:@"Works!!!"];

Upvotes: 1

Related Questions