SomeClass header
1 2 3 4 5 6 7 8 9 10 |
@interface SomeClass : NSObject { int number; //member variable } @property(nonatomic, assign) int number; -(void)method:(NSString*)threadName; @end |
SomeClass implementation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#import "SomeClass.h" @implementation SomeClass @synthesize number; -(void)method:(NSString*)threadName { for( int i = 0; i < 50;i++) { number = i; NSLog(@"Thread %@ processing on object %p 's method, member variable address: %p, number just changed to %d", threadName, self, &number, number); } NSLog(@"method - thread %@ number is now: %d", threadName, number); } @end |
main
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
-(void)process:(NSString*)threadName { SomeClass * aClass = [[SomeClass alloc] init]; [aClass method:threadName]; } .. .. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [NSThread detachNewThreadSelector:@selector(process:) toTarget:self withObject:@"A"]; [NSThread detachNewThreadSelector:@selector(process:) toTarget:self withObject:@"B"]; return YES; } |
log output:
Thread B processing on object 0x7fe839416a70 ‘s method, member variable address: 0x7fe839416a78, number just changed to 0
Thread B processing on object 0x7fe839416a70 ‘s method, member variable address: 0x7fe839416a78, number just changed to 1
Thread A processing on object 0x7fe83960e340 ‘s method, member variable address: 0x7fe83960e348, number just changed to 0
Thread A processing on object 0x7fe83960e340 ‘s method, member variable address: 0x7fe83960e348, number just changed to 1
Thread B processing on object 0x7fe839416a70 ‘s method, member variable address: 0x7fe839416a78, number just changed to 2
Thread B processing on object 0x7fe839416a70 ‘s method, member variable address: 0x7fe839416a78, number just changed to 3
Thread A processing on object 0x7fe83960e340 ‘s method, member variable address: 0x7fe83960e348, number just changed to 2
As you can see
Thread A processes on object 0x7fe83960e340
Thread B processes on object 0x7fe839416a70
The access different member variables, in particular
Thread A processes on object 0x7fe83960e340’s member variable 0x7fe83960e348
Thread B processes on object 0x7fe839416a70’s member variable 0x7fe839416a78
Both threads do their work on their own respective objects because those objects were allocated on the thread’s own stack in main’s
1 |
-(void)process:(NSString*)threadName |