forked from karelia/KSHTMLWriter
/
KSXMLAttributes.m
123 lines (90 loc) · 2.55 KB
/
KSXMLAttributes.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
//
// KSXMLAttributes.m
// Sandvox
//
// Created by Mike on 19/11/2010.
// Copyright 2010-2012 Karelia Software. All rights reserved.
//
#import "KSXMLAttributes.h"
#import "KSXMLWriter.h"
@implementation KSXMLAttributes
#pragma mark Dictionary Primitives
- (NSUInteger)count; { return [_attributes count] / 2; }
- (id)objectForKey:(id)aKey;
{
for (int i = 0; i < [_attributes count]; i+=2)
{
NSString *attribute = [_attributes objectAtIndex:i];
id value = [_attributes objectAtIndex:i+1];
if ([attribute isEqual:aKey]) // not -isEqualToString: on the offchance someone's crazy enough to pass in non-string key
{
return value;
}
}
return nil;
}
- (NSEnumerator *)keyEnumerator;
{
NSMutableArray *keys = [[NSMutableArray alloc] initWithCapacity:[self count]];
for (int i = 0; i < [_attributes count]; i+=2)
{
NSString *attribute = [_attributes objectAtIndex:i];
[keys addObject:attribute];
}
NSEnumerator *result = [keys objectEnumerator];
[keys release]; // the enumerator should retain the array
return result;
}
#pragma mark Lifecycle
- (id)init;
{
[super init];
_attributes = [[NSMutableArray alloc] initWithCapacity:2];
return self;
}
- (id)initWithXMLAttributes:(KSXMLAttributes *)info;
{
self = [super init]; // call super, so _attributes is still nil
_attributes = [info->_attributes mutableCopy];
return self;
}
- (void)dealloc;
{
[_attributes release];
[super dealloc];
}
- (void)setAttributesAsDictionary:(NSDictionary *)dictionary;
{
for (NSString *anAttribute in dictionary)
{
[self addAttribute:anAttribute value:[dictionary objectForKey:anAttribute]];
}
}
- (void)addAttribute:(NSString *)attribute value:(id)value;
{
NSParameterAssert(value);
// TODO: Ignore if the attribute is already present
[_attributes addObject:attribute];
[_attributes addObject:value];
}
- (void)close;
{
[_attributes removeAllObjects];
}
#pragma mark NSCopying
- (id)copyWithZone:(NSZone *)zone;
{
return [[[KSXMLAttributes class] alloc] initWithXMLAttributes:self];
}
#pragma mark Description
- (NSString *)description;
{
NSMutableString *result = [NSMutableString stringWithString:[super description]];
KSXMLWriter *writer = [[KSXMLWriter alloc] initWithOutputWriter:result];
[writer writeString:@" "];
[writer startElement:@"" attributes:self];
[writer endElement];
[writer release];
return result;
}
@end