Objective-C Pointers > pointing to properties
I have an NSInteger property of a custom class called 'estimatedTime', now, in my UITableView class I'm trying to pass this property as a pointer to a UITableViewCell. I can't seem to get it to work! I've tried the following:
NSInteger *poin开发者_开发百科ter = sharedManager.tempTask.&estimatedTime;
NSInteger *pointer = &sharedManager.tempTask.estimatedTime;
I get the errors: lvalue required as unary '&' operand and: expected identifier before '&' token
Can you not pass a pointer to a property? Is the property not just it self pointing to the ivar in my custom class? I need it as a pointer type so I can edit the value when a UITextField is changed inside the UITableViewCell.
Thanks and hope it makes sense!
Properties aren't variables; they are just syntactic sugar for get/set-style methods. Consequently, you can't take the address of a property.
As Marcelo said, you can't do this using the property itself.
You would either have to:
- Add a method to
tempTask
that returns a pointer to theestimatedTime
iVar (NSInteger *pointer = sharedManager.tempTask.estimatedTimePointer
) - Use a temporary
NSInteger
, taking its address for whatever calls you need, then copy the result intoestimatedTime
Option 1 is probably a really bad idea, because it breaks object encapsulation.
For using numbers in pointers I would suggest using a NSNumber* rather than a NSInteger* (an NSInteger is really an int). For example, if sharedManager.tempTask.estimatedTime is an NSInteger, you could do:
NSNumber *pointer = [NSNumber numberWithInt:sharedManager.tempTask.estimatedTime];
Now, when you want to use the int value for the number do:
NSInteger i = [n intValue];
The NSNumber * is a obj-c object so the usual retain/release/autorelease mechanisms apply.
Actually when you say Object1.Propertyxy.Property1
It is actually called as a FUNCTION rather than a VARIABLE/VALUE at some memory.
In your case "tempTask" will act as a function and "estimatedTime" as a argument and the result would be the RETURN of the function.
I know and completely agree that pointers are very favorable for increasing speed but in this case it is just useless as it would require storing that PROPERTY somewhere and thereafter referring to i, just a waste of time and memory, go for it only if you have to use that very specefic property a 100 times per run :D
Hope this helped, if it didn't just let me know, I'll be glad to help.
精彩评论