开发者

String as key in a mapping

I want to store an object in an NSMutableDictionary with a string key, so I have made the declaration like this:

[m_pMsgIdToStructMap setObject:pStruct 
                        forKey:[NSMutableString stringWithString:pStruct->szAsciiName]];

szAsciiName is declared as NSMutableString * in the .h file. I am not getting any warning or error, but I want to confirm whether the declaration that I'm making is correct.

EDITED:

Hi,

main.m
-------

#import <Foundation/Foundation.h>
#import "string.h"

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    stringss* stringsss = [[stringss alloc]init];
    //NSMutableString* strs = [[NSMutableString alloc]initWithFormat:"First"];
    [stringsss trail:@"First"]; //getting warning:Passing argument 1 of 'trail' from incompatible pointer type

    开发者_如何转开发[pool drain];
    return 0;
}

stringss.h
----------

#import <Foundation/Foundation.h>

typedef struct
{
    int a;
    int b;
    NSMutableString* szAsciiName;

}st;
@interface stringss : NSObject {

    NSMutableDictionary* m_map;

}
-(void)trail:(const char*)szAsciiName;

@end

stringss.m
---------

#import "string.h"

@implementation stringss

-(id)init
{
    if (self = [super init]) {
        m_map = [[NSMutableDictionary alloc]init];
        //pStruct->szAsciiName = [[NSMutableString alloc]init];
    }
    return self;
}
-(void)trail:(NSString*)szAsciiName
{
    st* pStruct = malloc(sizeof(st));
    st* pStruct1 = malloc(sizeof(st));

    pStruct->a = 10;
    pStruct->b = 20;
    pStruct->szAsciiName = [[NSMutableString alloc]init];
    pStruct->szAsciiName = (NSMutableString*)szAsciiName;

    [m_map setObject:(void*)pStruct forKey:szAsciiName];

    pStruct1 = (st*)[[m_map objectForKey:szAsciiName]bytes];
}

@end

I'm getting EXC_BAD_ACCESS exception also.


At a guess, pStruct is not an NSObject, its a raw structure (given your use of -> to dereference the szAsciiName).

That isn't going to work without more tweaking. You can make a CFDictionary hold on to non-NSObject's by installing customer release/retain handlers.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜