开发者

Storing/Extracting Objects to/from NSDictionary

开发者 https://www.devze.com 2023-04-13 07:09 出处:网络
I am getting errors using a NSDictionary when trying to assign it\'s contents to new variables/objects. Maybe this isn\'t posible? I thought it would be. I\'m also not sure if I can use non-Objective

I am getting errors using a NSDictionary when trying to assign it's contents to new variables/objects. Maybe this isn't posible? I thought it would be. I'm also not sure if I can use non-Objective C specific objects in the dictionary. Can you?

NSDictionary *preProcessResult = [[NSDictionary alloc] initWithDictionary: [self prePro开发者_运维技巧cessing:testImage]];
IplImage* resultImage = [preProcessResult objectForKey:@"ResultImage"];
int numChars = [preProcessResult objectForKey:@"NumberChars"];
[preProcessResult release];

And here is the method I am calling to create the dictionary:

- (NSDictionary*) preProcessing: (IplImage*) testImage {

//do stuff to image

NSDictionary *testImage_andNumChars = [NSDictionary dictionaryWithObjectsAndKeys:resultImage, 
@"ResultImage", numChars, @"NumberChars", nil];

return testImage_andNumChars;
}

Is this not the correct way to handle this? The error I get when I create the dictionary is:

"Cannot convert 'IplImage*' to 'objc_object*' in argument passing"

and when I retrieve the dictionary elements I get:

"Cannot convert 'objc_object*' to 'IplImage*' in initialization" and "Invalid conversion from 'objc_object*' to 'int' ".

I've read the Apple docs on NSDictionary which got me this far, but I am not sure where to go from here.

Thanks in advance.


Putting it shortly, NSDictionary values must be NSObjects.

You should store int as NSNumber using e.g.:

[NSNumber numberWithInt:numChars]

When retrieving the value you can use e.g.:

int numChars = [[preProcessResult objectForKey:@"NumberChars"] intValue];


IplImage is a strict and numchars is an int. since neither one is an objective c object, you cannot store them as such in the dictionary. You need to create an object that represents them. In the case of numchars, you should store an NSNumber object. To get the value back you would call intValue on the NSNumber you get back from objectForKey.

For the IplImage it is a little more complicated. You could wrap it in a class of its own, or you could extend NSValue.

The main thing is that The dictionary can only store objective c objects.


Also you cannot add an integer to a dictionary - it needs to be an object. So wrap your integer in a NSNumber and you should be ok.

0

精彩评论

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

关注公众号