Does Objective-C have an equivalent to java annotations?

前端 未结 8 1090
后悔当初
后悔当初 2020-12-28 09:10

Does Objective-C have an equivalent to java annotations?

What\'s I\'m trying to do is create a property and be able to somehow access some metadata about it.

8条回答
  •  死守一世寂寞
    2020-12-28 09:33

    Objective C does not support generics like in Java but ofcourse the language is very flexible that you can accomplish almost anything with simple tricks and knowledge. To implement a generic like feature you could create a category on NSArray class and create your own method to initialize the array and then check to see if the object is really the type of the object you want.

    I would write a simple category on NSArray to have such functionality. Say suppose, I want my array to hold objects of class MyClass only then my category would look like,

    @interface NSArray(MyCategory)
    
    @end
    
    @implementation NSArray(MyCategory)
    
    -(NSArray*)arrayWithMyClasses:(NSArray*)classes{
        if([classes count] > 0){
            NSMutableArray *array = [[NSMutableArray alloc] init];
            for(id anObj in classes){
                NSAssert([anObj isKindOfClass:[MyClass class]], @"My array supports only objetcts of type MyClass");
                [array addObject:anObj];
            }
            return array;
        }
        return nil;
    }
    @end 
    

    Of course, there is some limitations to it. Since you have created your own category, you should use your own method to initialize and create your own array.

提交回复
热议问题