NSMutableArray with a specific object type

You can specify that NSMutableArray can contain only a specific type of object. For example, if I want to store only such objects:

@interface MyObject : NSObject {
    UInt8 value; 
}

To be able to use an instance variable as follows:

- (void)myMethod:(NSMutableArray *)myArray{
    for (id myObject in myArray){
        [self otherMethod:myObject.value];
    }
}

because i get this error:

request for member 'value' in something not a structure or union

thanks for the help

+3
source share
6 answers

You get this error because for Objective-C, it myObjectis a non-type idthat does not support the property value. To make Objective-C aware that it always deals with myObjectthis loop, you have to say that the object myObjectis an instance myObject.

for (MyObject *myObject in myArray) {

, , value ivar , getter setter. , -value -setValue:, @property @synthesize, Objective-C .

+7

, Java/#, .

Cocoa . , ( -, ).

Objective-C, , " , , , , , ". , , , , , .

, respondsToSelector:.

, , . value - .

myObject.value. Objective-C .

Objective-C @protected, , - , - .

- (UInt8)value - (void)setValue:(UInt8)aValue .

.

+15

Objective-C . [myObject value] ( , -[value]). , .

0

- NSMutableArray, , .

0

NSMutableArray , . , [super addObject:xyz], .

0
source

maybe you can use the protocol:

@protocol Person <NSObject>
@end

@interface Person : NSObject <Person>
@end

for use:

NSArray<Person>*  personArray;
0
source

Source: https://habr.com/ru/post/1743161/


All Articles