What does id<…> mean in Objective-C?

后端 未结 5 1638
太阳男子
太阳男子 2021-01-03 22:48

I\'m trying to use Google Analytics in an iOS application, and I saw this portion of code :

id tracker = [[GAI sharedInstance] defaultTrack         


        
5条回答
  •  猫巷女王i
    2021-01-03 23:17

    1.The id type is designed to be a generic type which can hold any object type (in other words, id does not work with primitive types, such as ints and BOOLs).

    2.Imagine that you had a class that processed some external data. You don’t know or don’t care where the data comes from, but you should be prepared to handle many different types. Your data might come from a text file, where the contents might be read and passed into your method as an NSString. You might have to process the data in your own program somewhere else, and the data then would be as an NSArray or NSSet. Alternatively, the data could be coming from the internet as a JSON response, which must be parsed into an NSDictionary (don’t worry if you don’t know what JSON is…there’ll be something about this later down the road).

    - (void)processData:(id)someData {
    
        if ([someData isKindOfClass:[NSString class]])
            NSLog(@"input data is %@", someData);
    
        else if ([someData isKindOfClass:[NSArray class]]) {
            // Cast someData into an NSArray
            NSArray *dataArray = (NSArray *)someData;
            NSLog(@"First object in dataArray is %@", [dataArray objectAtIndex:0]);
        }
    
        else if ([someData isKindOfClass:[NSDictionary class]]) {
            // Cast someData into an NSDictionary
            NSDictionary *dataDict = (NSDictionary *)someData;
            NSLog(@"Keys in dataDict are %@", [dataDict allKeys]);
        }
    
        else if ([someData isKindOfClass:[NSData class]])
            NSLog(@"someData is a bag of bits.");
    
        else
            NSLog(@"someData is an unsupported type:\n%@", someData);
    }
    

    You can get more details on this link http://www.binpress.com/tutorial/learn-objectivec-objects-part-8-dynamic-typing/68

提交回复
热议问题