CFDictionaryGetValue()
I could not able to get the value for the key.
I have a structure pt(which is the value) and a wTiId,wTiId1(which is the key).
I am sure that something wrong i'm doing in the below code but i could not figure out what it is.
Timers.h
---------
#import <Foundation/Foundation.h>
struct session {
int a;
char c;
}pstruct;
@interface Timers : NSObject {
unsigned short wTiId;
unsigned short wTiId1;
}
-(void)timer;
@end
Timers.m
--------
#import "Timers.h"
@implementation Timers
-(id)init
{
if (self=[super init]) {
wTiId=71;
wTiId1=72;
}
return self;
}
-(void)dealloc
{
[super dealloc];
}
-(void)timer
{
struct session* pt = &pstruct;
pt->a=12;
pt->c='L';
CFDictionaryValueCallBacks cbvs = {0,NULL,NULL,NULL,NULL};
CFMutableDictionaryRef cfmdict = CFDictionaryCreateMutable(NULL,0,&kCFTypeDictionaryKeyCallBacks,&cbvs);
NSLog(@"Dict size:%d\n",((CFIndex)CFDi开发者_如何学GoctionaryGetCount(cfmdict)));
CFNumberRef tiId = CFNumberCreate(NULL,kCFNumberShortType,&wTiId);
CFNumberRef tiId1 = CFNumberCreate(NULL,kCFNumberShortType,&wTiId1);
CFDictionarySetValue(cfmdict,tiId,pt);
NSLog(@"Dict size:%d\n",((CFIndex)CFDictionaryGetCount(cfmdict)));
CFDictionarySetValue(cfmdict,tiId1,pt);
NSLog(@"Dict size:%d\n",((CFIndex)CFDictionaryGetCount(cfmdict)));
NSLog(@"The value is:%s",(CFDictionaryGetValue(cfmdict,tiId)));
CFRelease(tiId);
CFRelease(tiId1);
}
@end
main.m
------
#import <Foundation/Foundation.h>
#import "Timers.h"
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Timers* time = [[Timers alloc]init];
[time timer];
[pool drain];
return 0;
}
output
------
2011-05-15 14:52:54.857 timer[3511:a0f] Dict size:0
2011-05-15 14:52:54.861 timer[3511:a0f] Dict size:1
2011-05-15 14:52:54.861 timer[3511:a0f] Dict size:2
2011-05-15 14:52:54.862 timer[3511:a0f] The value is:
I tried with the format specifier "%@" also.Nothing gets printed when CFDictionaryGetValue () function is called.The return type of this function is const void*.
The result of CFDictionaryGetValue
is what you put in the dictionary.
You have to cast the result of CFDictionaryGetValue
to the right pointer type to access the structure members:
struct session *value = (struct session *) CFDictionaryGetValue(cfmdict,tiId);
NSLog(@"The value is %d and %c", value->a, value->c);
You cannot store structs in CFDictionarys, only pointers to structs will work. You cannot print the contents of the struct with the %s
format specifier.
精彩评论