开发者

How to change the property of UILabels which store in a NSMutableArray

i am going to just add one UILabel into array as example

NSMutablearray *labels = [[NSMutableArray alloc] init];
UILabel *newLabel = [[UILabel alloc] initWithFrame:CGRectMake(100,100,20,20)];
newLabel.center = CGPointMake(100, 100);
[labels addObject:newLabel];

then later i want to change newLabel.center by doing something like this

[labels objectAtIndex:1].center.x +=10;

this gives me an error "request for member "center" in someth开发者_如何学Cing not a structure or union"

then i try

    [labels objectAtIndex:1]->center.x +=10;

then this gives me another error said struct objc_object has no member named 'center'

how can i change the property of UILabel that is store in NSMutableArray?


You are getting this error because the return type of objectAtIndex: is simply id (which can be any object); NSArray is a generic container, when you retrieve an object from it, there's no way to know what type it is. You know, because you put the objects in it, but the compiler doesn't know.

You wrote:

[labels objectAtIndex:1].center.x +=10;

That's technically correct, but the compiler can't type check it. It's equivalent to writing this:

id object = [labels objectAtIndex:1];
object.center.x +=10;

The second line is where the error occurs: the compiler knows object is an Objective-C object, but it doesn't know what class, so it doesn't know what properties have been defined, etc. So instead it tries to parse it as a structure field member access, which it's not, and it fails.

If you instead write:

UILabel *label = [labels objectAtIndex:1];
label.center.x +=10;

Now the compiler knows that label is an instance of UILabel, it knows about the property definitions, and it can generate the correct code.

Now you have a second problem, because you are changing a value within a structure. The second line above is shorthand for:

label.center.x = label.center.x + 10;

This is again shorthand for a Objective-C method call:

[label center].x = [label center].x + 10;

Because the center point is a CGPoint struct, you have to get/set the entire point value at once, you can't just update the x or y member. So again, you need to do it like this:

UILabel *label = [labels objectAtIndex:1];
CGPoint c = label.center;
c.x += 10;
label.center = c;

That will do what you want.

If you're tempted to say Objective-C is a stupid language because you need all the temporary variables... well, maybe, but be fair and understand you hit on two special cases in one example.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜