Reputation: 1238
I have written a class which has a property, I want to add instances of this class into a mutable array and after that I want to set the num property of the instances. but I dont know the correct syntax. Please tell me the correct syntax or method to do this.
@interface ClassA : NSObject
@property int num;
-(void) method;
+(id) getClassAObj:(int)number;
@end
--------------------------------
#import "ClassA.h"
@implementation ClassA
@synthesize num;
-(void) method{
NSLog(@"ClassA method Called");
}
+(id) getClassAObj:(int)number {
ClassA *obj = [[ClassA alloc] init];
obj.num = number;
return obj;
}
@end
-----------------------
now in main I want to set the num property manually but I dont know what is the correct syntax
int main(int argc, const char * argv[])
{
@autoreleasepool {
// insert code here...
NSLog(@"Hello, World!");
NSMutableArray *array = [NSMutableArray arrayWithObjects:
[ClassA getClassAObj:9],
[ClassA getClassAObj:4], nil];
NSLog(@"%i",[[array objectAtIndex:0] num]);
NSLog(@"%i",[array[1] num]);
//array[1].num = 3; <--- Help needed here
//[[array[1]]num 3]; <--- this is also not correct syntax
NSLog(@"%i",[array[1] num]);
}
return 0;
}
I dont know If I am wrong with the syntax or may be it is not possible to set a property of an object inside an array
Upvotes: 1
Views: 1122
Reputation: 3152
Here you go:
ClassA *anObject = array[<index>];
[anObject setNum:<yourNumber>];
You can also use the [<array> objectAtIndex:<index>]
method, but the above is the newer way to do it.
Good Luck!
EDIT:
If you want to validate the object (so it will not crash, but it will also not work as expected) your code can look like this:
id anObject = array[<index>];
if ([anObject isKindOfClass:[NSClassFromString(@"ClassA")]]) {
[(ClassA *)anObject setNum:<number>];
}
If you want to validade the exact message (the setter in this case), you should check if the object responds to this selector. This is useful when you have objects of different classes, but they all respond to the message. It would look like this:
id anObject = array[<index>];
if ([anObject respondsToSelector:@selector(setNum:)) {
[anObject setNum:<number>];
}
Upvotes: 7
Reputation: 9132
array[1].num = 3;
This would work, however, the problem is, the compiler loses track of type information about an object if you put it in an array. The runtime still recognizes what kind of object it is. You just have to politely inform the compiler.
((ClassA *)(array[1])).num = 3;
Upvotes: 3