我用一些非客观的c代码写了这个方法,仪器告诉我有泄漏。不仅如此,而且免费(char *)崩溃......
任何帮助都将不胜感激。
由于
NSArray *keys = @[@"@\"NSMutableArray\""];
//Init result
id result = object;
//Iterate every key
for (id key in [dict allKeys]) {
//Convert key to const char
const char * c =(const char*)malloc(sizeof(uint32_t));
c = [key cStringUsingEncoding:NSASCIIStringEncoding];
//Use c to see if the class has this property
if (class_getProperty([object class], c)) {
//get the property
objc_property_t property = class_getProperty([result class], c);
//Get the property name and type
const char *name = (const char*)malloc(sizeof(uint32_t));
const char *type = (const char*)malloc(sizeof(uint32_t));
name = property_getName(property);
type =property_copyAttributeValue(property, "T");
//Cast const char to string
NSString *pNameString = [NSString stringWithFormat:@"%s",name];
NSString *typeString = [NSString stringWithFormat:@"%s",type];
//Add relationships
if ([keys containsObject:typeString]) {
//Get array of objects
NSArray *relationship = [dict objectForKey:pNameString];
NSMutableArray *allSubObjects = [[NSMutableArray alloc]init];
//Parse each individual object
for (NSDictionary *relationshipObj in relationship) {
//Create class from relationship
Class class = NSClassFromString(pNameString);
//Create object
id sub = [self makeObject:[[class alloc]init] fromDictionary:relationshipObj];
[allSubObjects addObject:sub];
}
[result setValue:allSubObjects forKey:pNameString];
}else{
//If so set the property for the key
[result setValue:[dict objectForKey:key] forKey:key];
}
free((char*)name);
free((char*)type);
free(property);
}else{
//NSLog(@"%@ did not respond to : %@", result, key);
}
free((void*)c);
}
//Return result
return result;
答案 0 :(得分:4)
它崩溃是因为你分配了c
,然后用cStringUsingEncoding:
返回覆盖了指针,然后尝试释放cStringusingEncoding
返回的代码,而你的代码并不拥有。此外,原始指针被泄露。
Frome cStringUsingEncoding
的{{3}}:
保证返回的C字符串仅在接收器被释放之前有效,或者直到当前存储器被清空为止,以先发生者为准。您应该复制C字符串或使用getCString:maxLength:encoding:如果它需要存储超出此时间的C字符串。