]> git.saurik.com Git - apple/objc4.git/blob - test/accessors.m
objc4-437.tar.gz
[apple/objc4.git] / test / accessors.m
1 #import <Foundation/Foundation.h>
2 #import <objc/runtime.h>
3 #include "test.h"
4
5 extern id objc_getProperty(id self, SEL _cmd, ptrdiff_t offset, BOOL atomic);
6 extern void objc_setProperty(id self, SEL _cmd, ptrdiff_t offset, id newValue, BOOL atomic, BOOL shouldCopy);
7
8 @interface Test : NSObject {
9 NSString *_value;
10 // _object is at the last optimized property offset
11 id _object __attribute__((aligned(64)));
12 }
13 @property(readonly) Class class;
14 @property(copy) NSString *value;
15 @property(assign) id object;
16 @end
17
18 typedef struct {
19 id isa;
20 NSString *_value;
21 // _object is at the last optimized property offset
22 id _object __attribute__((aligned(64)));
23 } TestDefs;
24
25 @implementation Test
26
27 // Question: why can't this code be automatically generated?
28
29 - (void)dealloc {
30 self.value = nil;
31 self.object = nil;
32 [super dealloc];
33 }
34
35 - (Class)class { return objc_getProperty(self, _cmd, 0, YES); }
36
37 - (NSString*)value { return (NSString*) objc_getProperty(self, _cmd, offsetof(TestDefs, _value), YES); }
38 - (void)setValue:(NSString*)inValue { objc_setProperty(self, _cmd, offsetof(TestDefs, _value), inValue, YES, YES); }
39
40 - (id)object { return objc_getProperty(self, _cmd, offsetof(TestDefs, _object), YES); }
41 - (void)setObject:(id)inObject { objc_setProperty(self, _cmd, offsetof(TestDefs, _object), inObject, YES, NO); }
42
43 - (NSString *)description {
44 return [NSString stringWithFormat:@"value = %@, object = %@", self.value, self.object];
45 }
46
47 @end
48
49 int main() {
50 NSAutoreleasePool *pool = [NSAutoreleasePool new];
51
52 NSMutableString *value = [NSMutableString stringWithUTF8String:"test"];
53 id object = [NSNumber numberWithInt:11];
54 Test *t = [[Test new] autorelease];
55 t.value = value;
56 [value setString:@"yuck"]; // mutate the string.
57 testassert(t.value != value); // must copy, since it was mutable.
58 testassert([t.value isEqualToString:@"test"]);
59
60 Class testClass = [Test class];
61 Class cls = t.class;
62 testassert(testClass == cls);
63 cls = t.class;
64 testassert(testClass == cls);
65
66 t.object = object;
67 t.object = object;
68
69 // NSLog(@"t.object = %@, t.value = %@", t.object, t.value);
70 // NSLog(@"t.object = %@, t.value = %@", t.object, t.value); // second call will optimized getters.
71
72 [pool drain];
73
74 succeed(__FILE__);
75
76 return 0;
77 }