Access NSMutableArray from a different class

删除回忆录丶 提交于 2019-12-02 15:21:41

问题


I have a class where a NSMutableArray object is formed, as so:

navBarColour = [[NSMutableArray alloc] initWithObjects:colourOfNavBar, nil];

I then have another class, which has the first class added to it properly, but it won't let me access the NSMutableArray from the first class. This line of code:

NSLog(@"%@", [HandlingPalettes.navBarColour objectAtIndex:0]);

Returns:

expected ':' before '.' token

But:

NSLog(@"%@", [navBarColour objectAtIndex:0]);

would work in the original class.

What am i doing wrong here?


回答1:


The dot notation is used differently in objective c that from c++ or java. In objective-c it is shorthand for accessing a property. You need to have defined a objective-c property first, like this:

in the .h file (INSIDE the interface tag)

@property (nonatomic, retain) NSMutableArray *navBarColor;

in the .m file (INSIDE the implementation tag)

@synthesize navBarColor;

Only then can you access the array with the dot notation.




回答2:


(Actually, futureelite7 & Radek S aren't strictly correct, in that you don't need @property declaration to use dot notation. If there's a getter method called navBarColour then the dot notation works fine for that too. But that's another issue.)

The declaration for the property navBarColour must visible to your code containing the NSLog. Yes, do post your header file, if you say the added @property declaration is also failing to compile then you have something weird going on. Make sure your other class' .m is including that header, and that HandlingPalettes's class isn't merely declared with a forward declaration say (@class Blah;).

But also, is HandlingPalettes a class or an instance?!? Identifiers starting with capitol letters by convention imply its a class name, so that's suspicious. If it's a class name, then that's surely not what you want.

(Regarding using dot notation without @property, if HandlingPalettes is indeed a class, then if you had the class method +(NSMutableArray*)navBarColour then when it would compile.)




回答3:


You must add a property to the object containing the array and synthesize it:

@property(nonatomic, retain) NSMutableArray *navBarColour;

Also, change the compiler to Clang and the error messages will be more clear, if you like.



来源:https://stackoverflow.com/questions/5240240/access-nsmutablearray-from-a-different-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!