Hur*_*rkS 2 iphone xmlwriter nsdictionary ios
我正在使用xmlWriter创建XML,我在NSDictionary中有值,它有几个键/值对,但是其中一些值是[NSNull null],我将每个值传递给它自己的NSString.
在我的XMLWriter方法中,我有一个if语句,检查这是否是对db的特定方法调用,如果是,那么我只想为不相等的NSString变量创建writeAttributes [NSNull null].
我不知道如何动态检查每个变量..我想也许我可以做一个if语句,但那不会起作用,因为只要其中一个变量不等于[NSNull null]那么它就会跳出这个当XML可能需要更多变量时,XMLWritter的一部分.
这是我失败的想法,所以你明白我想要做什么
// Method Params --->
- (NSMutableData *) addMethodParams
{
//allocate serializer (this is using the xmlWriter class)
id <XMLStreamWriter> xmlWriter = [[XMLWriter alloc] init];
[xmlWriter writeStartElement:@"Eng"];
[xmlWriter writeStartElement:@"Parameters"];
[xmlWriter writeStartElement:@"Vars"];
if ([methodName isEqualToString:@"SeriesSearch"]) // name of method currently being requested
{
if ((NSNull *) Series != [NSNull null]) { // if this is null then its jumped
[xmlWriter writeAttribute:@"Code" value:Series];
}
else if ((NSNull *) IDSeries != [NSNull null]){ //if this is !null then it enters the if statement however it then will jump out and not check over any of the other if statments
[xmlWriter writeAttribute:@"ManufacturerID" value:IDSeries];
}
//..
}
[xmlWriter writeEndElement];
[xmlWriter writeEndElement];
[xmlWriter writeEndElement];
Run Code Online (Sandbox Code Playgroud)
所以问题是如何将具有值的变量添加到我的xml中,停止变量为null?创建我猜一种动态的xml编写器.
通常,当您必须编写相同的代码超过两次(或甚至多于一次)时,您应该考虑创建方法或函数.所以你可以写一个像这样的方法:
- (void)writeAttribute:(NSString *)name ifNonNullValue:(id)value toWriter:(id<XMLStreamWriter>)writer {
if (value != [NSNull null]) {
[writer writeAttribute:name value:value];
}
}
Run Code Online (Sandbox Code Playgroud)
并像这样使用它:
[self writeAttribute:@"Code" ifNonNullValue:Series toWriter:xmlWriter];
[self writeAttribute:@"ManufacturerID" ifNonNullValue:IDSeries toWriter:xmlWriter];
...
Run Code Online (Sandbox Code Playgroud)
您还可以考虑添加一个类别XMLWriter.类别允许您将自己的方法添加到任何类.所以你可以添加这样的类别:
// XMLWriter+NonNull.h
#import "XMLWriter.h"
@interface XMLWriter (NonNull)
- (void)writeAttribute:(NSString *)name ifNonNullValue:(id)value;
@end
// XMLWriter+NonNull.m
@implementation XMLWriter (NonNull)
- (void)writeAttribute:(NSString *)name ifNonNullValue:(id)value {
if (value != [NSNull null]) {
[self writeAttribute:name value:value];
}
}
@end
Run Code Online (Sandbox Code Playgroud)
并像这样使用它:
// At top of file
#import "XMLWriter+NonNull.h"
...
[xmlWriter writeAttribute:@"Code" ifNonNullValue:Series];
[xmlWriter writeAttribute:@"ManufacturerID" ifNonNullValue:IDSeries];
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2355 次 |
| 最近记录: |