Releasing static variable & concurrent data protection questions...
Releasing static variable & concurrent data protection questions...
- Subject: Releasing static variable & concurrent data protection questions...
- From: Frederick C.Lee <email@hidden>
- Date: Mon, 15 Nov 2010 12:06:41 -0800
Environment: OS X (10.6.5) & iOS4+...
Scenario:
I have a static object (myNumber) that I use to accumulate a value through multiple iterations from concurrent blocks.
Here's what I have learned:
1) Best way to 'share' variables is via heap vs stack.
Hence, I've created a static object 'myNumber' that accumulates value.
The following is the code:
#import "ObjcBlocksViewController.h"
@implementation ObjcBlocksViewController
- (void)myPrintResults:(NSString *)desc {
static NSNumber *myNumber = nil;
if (myNumber == nil) {
myNumber = [[NSNumber alloc] initWithInt:0];
}
NSInteger myInteger = [myNumber integerValue];
myInteger += 5;
myNumber = [NSNumber numberWithInteger:myInteger];
NSLog(@"{myPrintResults} %@ myNumber = %@", desc, myNumber);
}
- (IBAction)buttonAction:(id)sender {
NSLog(@"{buttonAction} top");
dispatch_queue_t queue = dispatch_queue_create("com.mycompany.myButton", NULL);
dispatch_async(queue, ^(void) {
NSLog(@"----- {Outer-Block Operation} Top ----" );
[self myPrintResults:@"Main Loop"];
for (int k = 0; k < 10; k++) {
dispatch_async(dispatch_get_main_queue(), ^(void) {
[self myPrintResults:[NSString stringWithFormat:@"(%d)-Inner Loop-",k]];
});
}
NSLog(@"----- {Outer-Block Operation} Bottom ----" );
});
dispatch_release(queue);
NSLog(@"{buttonAction} bottom.");
} // end buttonAction().
- (void)dealloc {
[super dealloc];
}
@end
The output is expected:
...ObjcBlocks[1563:40b] {buttonAction} top
...ObjcBlocks[1563:40b] {buttonAction} bottom.
...ObjcBlocks[1563:1903] ----- {Outer-Block Operation} Top ----
...ObjcBlocks[1563:1903] {myPrintResults} Main Loop myNumber = 5
...ObjcBlocks[1563:40b] {myPrintResults} (0)-Inner Loop- myNumber = 10
...ObjcBlocks[1563:40b] {myPrintResults} (1)-Inner Loop- myNumber = 15
...
...ObjcBlocks[1563:40b] {myPrintResults} (9)-Inner Loop- myNumber = 55
...ObjcBlocks[1563:1903] ----- {Outer-Block Operation} Bottom ----
Questions:
1) How do I properly release my static NSNumber *myNumber after use?
It's static with a scope within an ObjC method so I can't release it in the dealloc().
2) Is the @synchronized() directive required within myPrintResults() to protect from possible thread crashes?
Regards,
Ric.
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden