Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
247 views
in Technique[技术] by (71.8m points)

iphone - Generic return type for primitives

Is there a return type for "any primitive" similar to the way you can use NSObject as the return type for any object? I tried using id, but the compiler was giving me an error that it was trying to convert a primitive to a reference.

Here's what I'm trying to do. :

-(void)setObject:(NSObject*)obj forKey:(NSString*)key {
    [sharedInstance.variables setObject:obj forKey:key];
}


-(NSObject*)getObjectForKey:(NSString*)key {
    return [sharedInstance.variables objectForKey:key];
}


-(void)setValue:(???)value forKey:(NSString*)key {
    [sharedInstance.variables setValue:value forKey:key];
}


-(???)getValueForKey:(NSString*)key {
    return [sharedInstance.variables valueForKey:key];
}

The alternative that I have though of is to use separate methods (getIntForKey, getFloatForKey, etc.) to access the values.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

1) Read Key-Value Coding Article in XCode documentation - all answers are there

2) There's an object NSValue, which resembles your "NSObject". NSValue can store plain-old-data inside itself.

PS

"Scalar and Structure Support Key-value coding provides support for scalar values and data structures by automatically wrapping, and unwrapping, of NSNumber and NSValue instance values. Representing Data as Objects The default implementations of valueForKey: and setValue:forKey: provide support for automatic object wrapping of the non-object data types, both scalars and structs. Once valueForKey: has determined the specific accessor method or instance variable that is used to supply the value for the specified key, it examines the return type or the data type. If the value to be returned is not an object, an NSNumber or NSValue object is created for that value and returned in its place. Similarly, setValue:forKey: determines the data type required by the appropriate accessor or instance variable for the specified key. If the data type is not an object, then the value is extracted from the passed object using the appropriate -Value method."


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...