开发者

Using a property of a subclass of an object

开发者 https://www.devze.com 2023-04-06 07:02 出处:网络
My code functions properly, but I am getting warnings, so I think I can do this better.I have a subclass of NSObject (Objects) and I have a subclass of Objects (subObject).I have a property declared i

My code functions properly, but I am getting warnings, so I think I can do this better. I have a subclass of NSObject (Objects) and I have a subclass of Objects (subObject). I have a property declared in subObjects. I store many objects that are all different subclasses of Objects in a single NSMutableArray. Sometimes, I go through the array and do certain things to certain objects. I read from my array like this:

//I have declared an Objects "myObject" earlier in my code.
开发者_开发百科//c is an int used to select an object from the array
myObject = [arrayObjects objectAtIndex:c];

In this case, I am accessing my property declared in subObject as

[myObject property]

The code works because I have it set up so it should not be able to get to this piece of code without being a subObject. However, I am getting a warning because the computer does not know this. It only knows that myObject is an Objects, not a subObject. How do I fix this and get rid of the warning?


If it is sure that all objects in the NSMutableArray are of type SubObject (type names should start with an upper case character), then you have these possibilities:

  • you can declare the item you extract as SubObject directly:

    SubObject *myObject = [arrayObjects objectAtIndex: c];
    [myObject setProperty: 17];
    
  • or you cast:

    Object *myObject = [arrayObjects objectAtIndex: c];
    [(SubObject*)myObject setProperty: 17];
    
  • or you simply use id. If you use id, the compiler assumes nothing and will not issue a warning:

    id myObject = [arrayObjects objectAtIndex: c];
    [myObject setProperty: 17];
    


You have to make sure that the object you get from the array is declared of the subObject type BEFORE your "making sure" that all is correct. Then the compiler will not give the warning anymore...

eg. something like:

Object objO;

objO = [myarray objectAtIndex: n];

if (myMakingSure) {
    SubObject objS;
    objS = (SubObject) objO;
    x= [objS getProperty];
}

ps also make sure, that you accept answers if they are correct - otherwise one may be hesitant to answer your questions... (I didn't know at the very beginning and also got a nice note about that)

0

精彩评论

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

关注公众号