【发布时间】:2011-07-06 16:37:40
【问题描述】:
全部,
我正在尝试将 NSMutableDictionary“响应”发送给我的另一个班级,或者更确切地说,让另一个班级从这个班级中提取字典。当其他类使用“getResponse”方法时,它返回 null。
我附上的代码是我的 XML 解析器,它将我需要的信息放入字典中。最底部是在 NSLog 中显示“(null)”的方法。我已经为你评论了。
编辑:我确实使用 initXMLParser 方法在另一个类中进行初始化。但即便如此,在这个类中访问甚至都行不通。在显示响应字典的 getResponse 方法中,NSLog 只显示“TEST(null)”。
#import "XMLParser.h"
@implementation XMLParser
@synthesize response;
- (id)init
{
self = [super init];
if (self) {
// Initialization code here.
}
return self;
}
- (XMLParser *) initXMLParser //not sure if this is necessary anymore - CHECK THIS
{
self = [super init];
// init array of return data
NSLog(@"Initializing self and super...");
response = [[NSMutableDictionary alloc] init];
count = 1;
return self;
}
//Gets Start Element of SessionData
- (void)parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qualifiedName
attributes:(NSDictionary *)attributeDict
{
if ([elementName isEqualToString:@"SessionData"])
{
NSLog(@"Found SessionData in the return XML! Continuing...");
//response is a NSMutableArray instance variable (see .h of this)
if (!response)//if array is empty, it makes it!
{
NSLog(@"Dictionary is empty for some reason, creating...");
response = [[NSMutableDictionary alloc] init];
count=1;
}
return;
}
else
{
currentElementName = elementName;
NSLog(@"Current Element Name = %@", currentElementName);
return;
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if (!currentElementValue) {
// init the ad hoc string with the value
currentElementValue = [[NSMutableString alloc] initWithString:string];
} else {
// append value to the ad hoc string
[currentElementValue setString:string];
NSLog(@"Processing value for : %@", string);
}
}
//Gets End Element of SessionData
- (void)parser:(NSXMLParser *)parser
didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName {
if ([elementName isEqualToString:@"SessionData"])
{
// We reached the end of the XML document
//dumps dictionary into log
NSLog(@"Dump:%@", [response description]);
return;
}
else
{
//Adds key and object to dictionary
[response setObject:currentElementValue forKey:currentElementName];
NSLog(@"Set values, going around again... brb.");
}
currentElementValue = nil;
currentElementName = nil;
}
- (NSMutableDictionary*)getResponse
{
NSLog(@"%@", [self response]; //THIS RETURNS NULL
return response;
}
@end
【问题讨论】:
-
我没有看到返回
response的方法?- (NSDictionary *)response在哪里? -
有了这个属性,他还需要一个吗?
-
!response不测试response指向的对象是否为空;它测试该变量是否指向任何对象。空字典与没有字典有很大不同;您正在测试后者。
标签: iphone objective-c cocoa nsmutabledictionary