I have a question on thread safety while using NSMutableDictionary.
The main thread is reading data from NSMutableDictionary where:
key is NSString
value is UIImage
An asynchronous thread is writing data to above dictionary (using NSOperationQueue)
How do I make the above dictionary thread safe?
Should I make the NSMutableDictionary property atomic? Or do I need to make any additional changes?
#property(retain) NSMutableDictionary *dicNamesWithPhotos;
NSMutableDictionary isn't designed to be thread-safe data structure, and simply marking the property as atomic, doesn't ensure that the underlying data operations are actually performed atomically (in a safe manner).
To ensure that each operation is done in a safe manner, you would need to guard each operation on the dictionary with a lock:
// in initialization
self.dictionary = [[NSMutableDictionary alloc] init];
// create a lock object for the dictionary
self.dictionary_lock = [[NSLock alloc] init];
// at every access or modification:
[object.dictionary_lock lock];
[object.dictionary setObject:image forKey:name];
[object.dictionary_lock unlock];
You should consider rolling your own NSDictionary that simply delegates calls to NSMutableDictionary while holding a lock:
#interface SafeMutableDictionary : NSMutableDictionary
{
NSLock *lock;
NSMutableDictionary *underlyingDictionary;
}
#end
#implementation SafeMutableDictionary
- (id)init
{
if (self = [super init]) {
lock = [[NSLock alloc] init];
underlyingDictionary = [[NSMutableDictionary alloc] init];
}
return self;
}
- (void) dealloc
{
[lock_ release];
[underlyingDictionary release];
[super dealloc];
}
// forward all the calls with the lock held
- (retval_t) forward: (SEL) sel : (arglist_t) args
{
[lock lock];
#try {
return [underlyingDictionary performv:sel : args];
}
#finally {
[lock unlock];
}
}
#end
Please note that because each operation requires waiting for the lock and holding it, it's not quite scalable, but it might be good enough in your case.
If you want to use a proper threaded library, you can use TransactionKit library as they have TKMutableDictionary which is a multi-threaded safe library. I personally haven't used it, and it seems that it's a work in progress library, but you might want to give it a try.
Nowadays you'd probably go for #synchronized(object) instead.
...
#synchronized(dictionary) {
[dictionary setObject:image forKey:name];
}
...
#synchronized(dictionary) {
[dictionary objectForKey:key];
}
...
#synchronized(dictionary) {
[dictionary removeObjectForKey:key];
}
No need for the NSLock object any more
after a little bit of research I want to share with you this article :
Using collection classes safely with multithreaded applications
http://developer.apple.com/library/mac/#technotes/tn2002/tn2059.html
It looks like notnoop's answer may not be a solution after all. From threading perspective it is ok, but there are some critical subtleties. I will not post here a solution but I guess that there is a good one in this article.
I have two options to using nsmutabledictionary.
One is:
NSLock* lock = [[NSLock alloc] init];
[lock lock];
[object.dictionary setObject:image forKey:name];
[lock unlock];
Two is:
//Let's assume var image, name are setup properly
dispatch_async(dispatch_get_main_queue(),
^{
[object.dictionary setObject:image forKey:name];
});
I dont know why some people want to overwrite setting and getting of mutabledictionary.
Even the answer is correct, there is an elegant and different solution:
- (id)init {
self = [super init];
if (self != nil) {
NSString *label = [NSString stringWithFormat:#"%#.isolation.%p", [self class], self];
self.isolationQueue = dispatch_queue_create([label UTF8String], NULL);
label = [NSString stringWithFormat:#"%#.work.%p", [self class], self];
self.workQueue = dispatch_queue_create([label UTF8String], NULL);
}
return self;
}
//Setter, write into NSMutableDictionary
- (void)setCount:(NSUInteger)count forKey:(NSString *)key {
key = [key copy];
dispatch_async(self.isolationQueue, ^(){
if (count == 0) {
[self.counts removeObjectForKey:key];
} else {
self.counts[key] = #(count);
}
});
}
//Getter, read from NSMutableDictionary
- (NSUInteger)countForKey:(NSString *)key {
__block NSUInteger count;
dispatch_sync(self.isolationQueue, ^(){
NSNumber *n = self.counts[key];
count = [n unsignedIntegerValue];
});
return count;
}
The copy is important when using thread unsafe objects, with this you could avoid the possible error because of unintended release of the variable. No need for thread safe entities.
If more queue would like to use the NSMutableDictionary declare a private queue and change the setter to:
self.isolationQueue = dispatch_queue_create([label UTF8String], DISPATCH_QUEUE_CONCURRENT);
- (void)setCount:(NSUInteger)count forKey:(NSString *)key {
key = [key copy];
dispatch_barrier_async(self.isolationQueue, ^(){
if (count == 0) {
[self.counts removeObjectForKey:key];
} else {
self.counts[key] = #(count);
}
});
}
IMPORTANT!
You have to set an own private queue without it the dispatch_barrier_sync is just a simple dispatch_sync
Detailed explanation is in this marvelous blog article.
In some cases you might NSCache class. The documentation claims that it's thread safe:
You can add, remove, and query items in the cache from different threads without having to lock the cache yourself.
Here is article that describes quite useful tricks related to NSCache
Related
Ok, im a bit lost with this one, i am currently trying to run a background core data operation using a second ManagedObjectContext with its type set to NSPrivateQueueConcurrencyType and failing miserably with the above error.
I have a custom subclass of NSOperation, which is being passed an NSArray of strings, and the PersistentStoreCoordinator from the main thread, it then creates its own ManagedObjectContext, runs a query and performs and operation.
Here is the code from the class:
//
// ProcessProfanity.m
// Hashtag Live Desktop
//
// Created by Gareth Jeanne on 24/03/2014.
// Copyright (c) 2014 Gareth Jeanne. All rights reserved.
//
#import "ProcessProfanity.h"
#import "Tweet.h"
static const int ImportBatchSize = 250;
#interface ProcessProfanity ()
#property (nonatomic, copy) NSArray* badWords;
#property (nonatomic, strong) NSManagedObjectContext* backgroundContext;
#property (nonatomic, strong) NSPersistentStoreCoordinator* persistentStoreCoordinator;
#end
#implementation ProcessProfanity
{
}
- (id)initWithStore:(NSPersistentStoreCoordinator*)store badWords:(NSArray*)words
{
self = [super init];
if(self) {
self.persistentStoreCoordinator = store;
self.badWords = words;
}
return self;
}
- (void)main
{
_backgroundContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
_backgroundContext.persistentStoreCoordinator = [self persistentStoreCoordinator];
_backgroundContext.undoManager = nil;
[_backgroundContext performBlockAndWait:^
{
[self import];
}];
}
- (void)import
{
//Create new fetch request
NSFetchRequest *request = [[NSFetchRequest alloc] init];
//Setup the Request
[request setEntity:[NSEntityDescription entityForName:#"Tweet" inManagedObjectContext:self.backgroundContext]];
NSError *error = nil;
//Create an array from the returned objects
NSArray* tweetsToProcess = [self.backgroundContext executeFetchRequest:request error:&error];
NSAssert2(tweetsToProcess != nil && error == nil, #"Error fetching events: %#\n%#", [error localizedDescription], [error userInfo]);
for (Tweet* tweetToCheck in tweetsToProcess){
__block NSString *result = nil;
[self.badWords indexOfObjectWithOptions:NSEnumerationConcurrent
passingTest:^(NSString *obj, NSUInteger idx, BOOL *stop)
{
if (tweetToCheck){
if ([tweetToCheck.text rangeOfString:obj].location != NSNotFound)
{
result = obj;
*stop = YES;
//return YES;
}
}
return NO;
}];
if (!result){
//DDLogVerbose(#"The post does not contain any of the words from the naughty list");
if(tweetToCheck){
tweetToCheck.profanity = [NSNumber numberWithBool:false];
}
}
else{
if(tweetToCheck){
//DDLogVerbose(#"The string contains '%#' from the the naughty list", result);
tweetToCheck.profanity = [NSNumber numberWithBool:true];
}
}
}
[self.backgroundContext save:NULL];
}
#end
And this is how i am calling it:
-(void)checkForProfanity{
if(!self.operationQueue){
self.operationQueue = [[NSOperationQueue alloc] init];
}
NSArray* termsToPass = [self.filterTerms copy];
ProcessProfanity* operation = [[ProcessProfanity alloc] initWithStore:self.persistentStoreCoordinator badWords:termsToPass];
[self.operationQueue addOperation:operation];
}
Edit 1
The specific line i seem to be getting the error on, or at least where Xcode is breaking is:
if ([tweetToCheck.text rangeOfString:obj].location != NSNotFound)
I have managed to narrow this down a bit, the NSArray that contains the list of terms to search the strings for is potentially quite large, possibly over a 1,000 NSStrings. If i test with an array of that size, i get the issue. However if i reduce the array to around 15 NSStrings, i do not get the error, so i don't think this is necessarily a thread related issue, i'm wondering if the array is getting released in the main thread. I have modified the code to make a deep copy, and then a __block copy as follows, but it doesn't seem to have helped.
self.badWords = [[NSArray alloc] initWithArray:words copyItems:YES];
and
for (Tweet* tweetToCheck in tweetsToProcess){
__block NSArray *array = [[NSArray alloc] initWithArray:self.badWords copyItems:YES];
__block NSString *result = nil;
[array indexOfObjectWithOptions:NSEnumerationConcurrent
In fact, at the point where Xcode breaks, if i PO array, i get an object not found message, but if i po result, i correct get an object returned that is nil.
Edit 2
So i have made the following changes, with no change:
Made the NSArray strong rather than copy:
#property (nonatomic, strong) NSArray* badWords;
And made it a copy when allocated:
self.badWords = [[NSArray alloc] initWithArray:words copyItems:YES];
And created a local copy of the NSArray with the ___block declaration inside the actual method processing the objects:
__block NSArray *array = [[NSArray alloc] initWithArray:self.badWords copyItems:YES];
Which should surely mean it sticks around for the life of the ProcessProfanity object?
Am i wrong in expecting to be able to PO the array from the breakpoint within the block?
In this instance the error message "error: NULL _cd_rawData but the object is not being turned into a fault" indicates that you are accessing a managed object outside of its context. Basically your fetch returns all the Tweets from your persistent store as faults. Once you try and access a property on the Managed Object, Core Data will fire a fault and fetch the full object from the store.
By calling the NSArray method indexOfObjectWithOptions:passingTest: with an option of NSEnumerationConcurrent you are implying that you want to perform asynchronous execution on the elements in your array. The keyword concurrent indicates that multiple threads can be used to operate on the array elements.
In your context this means that accessing a managed object inside this block might result in accessing it on a different thread from the managed object context that owns the object. So when you access tweetToCheck.text in your conditional check - if ([tweetToCheck.text rangeOfString:obj].location != NSNotFound), under the hood Core Data is fetching that managed object from the persistent store and returning it to a thread that is not part of the managed object contexts thread.
Furthermore, it is not necessary to use the method indexOfObjectWithOptions:passingTest: since you are not actually interested in the result of this operation.
It seems to me that it might be more convenient for you to use an NSSet as you are only testing to see whether or not a given tweet word exists in your profane words. Quoting the documentation for NSSet: "You can use sets as an alternative to arrays when the order of elements isn’t important and performance in testing whether an object is contained in the set is a consideration". Clearly this seems to meet your criteria.
So your init would look like:
-(id)initWithStore:(NSPersistentStoreCoordinator*)store
badWords:(NSSet*)badWords
{
self = [super init];
if(self) {
self.persistentStoreCoordinator = store;
self.badWords = [words copy];
}
return self;
}
Since you are only interested in updating tweets that have not yet been tagged for profanity you would probably only want to fetch tweets that haven't been flagged profane:
//Create new fetch request
NSFetchRequest *request = [[NSFetchRequest alloc] init];
//Setup the Request
[request setEntity:[NSEntityDescription entityForName:#"Tweet" inManagedObjectContext:self.backgroundContext]];
[request setPredicate:[NSPredicate predicateWithFormat:#"profanity = NO"]];
Now that you have an array of tweets that are not profane you could iterate through your tweets and check each word if it contains a profane word. The only thing you will need to deal with is how to separate your tweet into words (ignoring commas and exclamation marks etc). Then for each word you are going to need to strip it of diacritics and probably ignore the case. So you would end up with someone along the lines of:
if([self.badWords containsObject:badWordString]) {
currentTweet.profanity = [NSNumber numberWithBOOL:YES];
}
Remember, you can run predicates on an NSSet so you could actually perform a case and diacritic insensitive query:
NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:#"SELF = %#[cd]",wordToCheck];
BOOL foundABadWord = ([[[self.badWords filteredSetUsingPredicate:searchPredicate] allObjects] count] > 0);
Another thing you might want to consider is removing duplicate words in your tweets, you don't really want to perform the same check multiple times. So depending on how you find the performance you could place each word of your tweet into an NSSet and simply run the query on the unique words in your tweet:
if([[self.badWords intersectsSet:tweetDividedIntoWordsSet]) {
//we have a profane tweet here!
}
Which implementation you choose is up to you but assuming you are only using english in your app you are definitely going to want to run a case and diacritic insensitive search.
EDIT
One final thing to note is that no matter how much you try, people will always be the best means of detecting profane or abusive language. I encourage you to read this SO's post on detecting profanity - How do you implement a good profanity filter?
Ok, so still not quite sure what was going on, but i followed Daniels advice and re-wrote the indexOfObjectWithOptions method and now it's working. For completeness, and so it hopefully helps someone else, this is what i ended up doing.
DDLogInfo(#"Processing posts to check for bad language");
for (Tweet* tweetToCheck in tweetsToProcess){
__block NSArray *array = [[NSArray alloc] initWithArray:self.badWords copyItems:YES];
__block NSString *result = nil;
NSRange tmprange;
for(NSString *string in array) {
tmprange = [tweetToCheck.text rangeOfString:[NSString stringWithFormat:#" %# ", string]];
if (tmprange.location != NSNotFound) {
result = string;
DDLogVerbose(#"Naughty Word Found: %#", string);
break;
}
}
if (!result){
//DDLogVerbose(#"The post does not contain any of the words from the naughty list");
if(tweetToCheck){
tweetToCheck.profanity = [NSNumber numberWithBool:false];
}
}
else{
if(tweetToCheck){
//DDLogVerbose(#"The string contains '%#' from the the naughty list", result);
tweetToCheck.profanity = [NSNumber numberWithBool:true];
}
}
I'm a developer from Python world used to using exceptions. I found in many places that using exceptions is not so wise here, and did my best to convert to NSErrors when needed. but then I encounter this:
NSMutableArray *results;
for (NSDictionary *dict in dicts)
{
// Memory management code omitted
SomeModel *model = [[SomeModel alloc] init];
model.attr1 = [[dict objectForKey:#"key1"] integerValue];
model.attr2 = [[dict objectForKey:#"key2"] integerValue];
model.attr3 = [[dict objectForKey:#"key3"] integerValue];
model.attr4 = [[dict objectForKey:#"key4"] integerValue];
[results addObject:model];
}
with some of the objects in dict containing NSNull, which would result an "unrecognized selector" exception. In that case, I want to drop that datum completely. My first instinct is to wrap the whole content of the for block into a #try-#catch block:
NSMutableArray *results;
for (NSDictionary *dict in dicts)
{
#try
{
SomeModel *model = [[SomeModel alloc] init];
model.attr1 = [[dict objectForKey:#"key1"] integerValue];
model.attr2 = [[dict objectForKey:#"key2"] integerValue];
model.attr3 = [[dict objectForKey:#"key3"] integerValue];
model.attr4 = [[dict objectForKey:#"key4"] integerValue];
[results addObject:model];
}
#catch(NSException *exception)
{
// Do something
}
}
But is this a good approach? I can't come up with a solution without repeating checks on each variable, which is really ugly IMO. Hopefully there are alternatives to this that haven't occur to me. Thanks in advance.
The proper Objective-C way to do this would be:
for (NSDictionary *dict in dicts)
{
if (! [dict isKindOfClass:[NSDictionary class]])
continue;
// ...
}
Testing if a receiver can respond to a message before sending it is a typical pattern in Objective-C.
Also, take note that exceptions in Objective-C are always a programmer error and are not used for normal execution flow.
Many people use a category on NSDictionary for these cases:
- (id)safeObjectForKey:(id)aKey
{
id obj = [self objectForKey:aKey];
if ([obj isKindOfClass:[NSNull class]])
{
return nil;
}
return obj;
}
You still need to make sure, that your dict is an actual dictionary instance.
In the end I decided to solve the problem using KVC. Something like this:
- (id)initWithPropertyDictionary:(NSDictionary *)dict
lookUpTable:(NSDictionary *)keyToProperty
{
self = [self init];
for (NSString *key in dict)
{
NSString *propertyName;
if ([keyToProperty objectForKey:key])
propertyName = [keyToProperty objectForKey:key];
else
propertyName = key;
if ([[dict objectForKey:key] isKindOfClass:[NSNull class]])
{
[self release];
return nil;
}
else
{
[self setValue:[dict objectForKey:key] forKey:propertyName];
}
}
}
The setback of this resolution is that I'll have to use NSNumber for my properties, but for JSON data there is really no distinction between floating numbers and integers, so this is fine.
And if you really want primitive types, you can couple this method with custom setters that converts those NSNumbers into appropriate types.
With this, all you need to do is check for nil before adding the object into the array. Much cleaner everywhere except the model class.
Thanks to jaydee3 for inspiring me to focus on changing the model class.
So here is a partial sample of the relevant code.
static NSMutableArray *radioInputArray;
static NSMutableArray *buttonsArray;
- (IBAction)lookForRadioButtons:(id)sender {
// NSLog(#"Testing");
NSError *error;
NSString *radiostr = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"getRadios" ofType:#"txt"] encoding:NSASCIIStringEncoding error: &error] ;
if (radiostr == nil)
{
NSLog (#"Error! %#", error);
}
else
{
NSLog(#"%#",radiostr);
NSString *radiotxt= [webView stringByEvaluatingJavaScriptFromString:radiostr];
NSLog(#"%#", radiotxt);
NSArray *myRadios = [radiotxt componentsSeparatedByString:#"::"];
[radioInputArray addObjectsFromArray:myRadios];
NSLog(#"%d", myRadios.count);
NSLog(#"Number of buttons in global radio array %d", radioInputArray.count);
NSLog(#"%d", scrollViewer.subviews.count);
}
}
So it throws no exceptions and seems to work properly except after addObjectsFromArray:, my count in the global NSMutableArray is 0 (the count in the myRadios = 56). I am pretty sure they should be equal at this point but are not. I have declared my NSMutableArray up near the top so that it can be globally accessed. Am I missing something such as allocating and initializing this? Does it not do that automatically like in C#? Again, this is my first foray into the Objective-C world from Windows programming so please be gentle yet feel free to be critical.
Your two global arrays are not initialized.
The lines
static NSMutableArray *radioInputArray;
static NSMutableArray *buttonsArray;
just define the two variables as pointers to NSMutableArray, so you need to get them to point at an actual instance of the class NSMutableArray.
Somewhere in your initialization code, or through an accessor (best if a class method), you should set the variables to an empty, newly allocated NSMutableArray.
Here is a way to do it:
+ (NSMutableArray*)radioInputArray
{
if (!radioInputArray) {
radioInputArray = [[NSMutableArray alloc] init];
}
return radioInputArray;
}
Then use the accessor in your code instead of the global variable.
It may happen if your radioInputArray is nil,
you didn't initialize the array
you need to add
[[radioInputArray alloc] init];
before you do anything with radioInputArray
Good place for initialising object is "init" method in Global class
Ex.
-(id)init
{
if (self=[super init]) {
self.globalAllArtworkArray=[[NSMutableArray alloc] init];
self.globalCollectionArray=[[NSMutableArray alloc] init];
self.globalLookbookArray=[[NSMutableArray alloc] init];
}
return self;
}
+(ASNGlobalClass *)shareManager
{
static ASNGlobalClass *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
I have an array of NSMutableDictionary objects which are displayed in a master–detail interface which has a few text fields and a bunch of check boxes. The controls are bound to the dictionary keys, accessed through an array controller's selection.
I'd like to add some logic which clears one check box when another is cleared, and restores the original value if it's rechecked in the same session. Since I need to associate storage with the dictionary, and need to add code too, I thought I'd use composition to extend NSMutableDictionary.
Here's what I've done:
I created a LibraryEntry subclass which contains an NSMutableDictionary.
I implemented forwardInvocation:, respondsToSelector:, methodSignatureForSelector:, and after some trial-and-error valueForUndefinedKey:.
I created my forwarder objects.
I left the bindings as they were.
It loads up the data just fine, but I'm guessing that KVO won't work correctly. I'm guessing the binder is calling addObserver: on the my object but I haven't implemented anything special to handle it.
I thought of simply overriding addObserver: and forwarding the message to the dictionary. But if I do that the observeValueForKey: notifications won't originate from my object (the original receiver of addObserver), but from the dictionary.
Before I tried to implement more transparent forwarding for these KVO calls, I thought ... this is getting messy. I keep reading "use composition, not subclassing" to get behavior like this. Is it just the wrong pattern for this situation? Why? Because of KVO?
It seems like I'd have cleaner results if I abandon composition and choose one of these alternatives:
Use decorators, with one instance observing each dictionary
Store the transient keys in the dictionary and have the controller remove them before saving
Dispense with the dictionary and declare properties instead
Here's my code, in case it's helpful (values is the dictionary):
- (void)forwardInvocation:(NSInvocation *)anInvocation {
if ([values respondsToSelector:[anInvocation selector]])
[anInvocation invokeWithTarget:values];
else
[super forwardInvocation:anInvocation];
}
- (BOOL)respondsToSelector:(SEL)aSelector {
if ( [super respondsToSelector:aSelector] )
return YES;
else
return [values respondsToSelector:aSelector];
}
- (NSMethodSignature*)methodSignatureForSelector:(SEL)selector {
NSMethodSignature* signature = [super methodSignatureForSelector:selector];
if (!signature) signature = [values methodSignatureForSelector:selector];
return signature;
}
-(id)valueForUndefinedKey:(NSString *)key {
return [values valueForKey:key];
}
I think with a combination of Objective-C associated storage, and some blocks, you could hook up arbitrary behaviors to a dictionary (or any other KVO compliant object) and solve your problem that way. I cooked up the following idea that implements a generic KVO-triggers-block mechanism and coded up and example that appears to do the sort of thing you want it to do, and does not involve subclassing or decorating foundation collections.
First the public interface of this mechanism:
typedef void (^KBBehavior)(id object, NSString* keyPath, id oldValue, id newValue, id userInfo);
#interface NSObject (KBKVOBehaviorObserver)
- (void)addBehavior: (KBBehavior)block forKeyPath: (NSString*)keyPath options: (NSKeyValueObservingOptions)options userInfo: (id)userInfo;
- (void)removeBehaviorForKeyPath: (NSString*)keyPath;
#end
This will allow you to attach block-based observations/behaviors to arbitrary objects. The task you describe with the checkboxes might look something like this:
- (void)testBehaviors
{
NSMutableDictionary* myModelDictionary = [NSMutableDictionary dictionary];
KBBehavior behaviorBlock = ^(id object, NSString* keyPath, id oldValue, id newValue, id userInfo)
{
NSMutableDictionary* modelDictionary = (NSMutableDictionary*)object;
NSMutableDictionary* previousValues = (NSMutableDictionary*)userInfo;
if (nil == newValue || (![newValue boolValue]))
{
// If the master is turning off, turn off the slave, but make a note of the previous value
id previousValue = [modelDictionary objectForKey: #"slaveCheckbox"];
if (previousValue)
[previousValues setObject: previousValue forKey: #"slaveCheckbox"];
else
[previousValues removeObjectForKey: #"slaveCheckbox"];
[modelDictionary setObject: newValue forKey: #"slaveCheckbox"];
}
else
{
// if the master is turning ON, restore the previous value of the slave
id prevValue = [previousValues objectForKey: #"slaveCheckbox"];
if (prevValue)
[modelDictionary setObject:prevValue forKey: #"slaveCheckbox"];
else
[modelDictionary removeObjectForKey: #"slaveCheckbox"];
}
};
// Set the state...
[myModelDictionary setObject: [NSNumber numberWithBool: YES] forKey: #"slaveCheckbox"];
[myModelDictionary setObject: [NSNumber numberWithBool: YES] forKey: #"masterCheckbox"];
// Add behavior
[myModelDictionary addBehavior: behaviorBlock forKeyPath: #"masterCheckbox" options: NSKeyValueObservingOptionNew userInfo: [NSMutableDictionary dictionary]];
// turn off the master
[myModelDictionary setObject: [NSNumber numberWithBool: NO] forKey: #"masterCheckbox"];
// we now expect the slave to be off...
NSLog(#"slaveCheckbox value: %#", [myModelDictionary objectForKey: #"slaveCheckbox"]);
// turn the master back on...
[myModelDictionary setObject: [NSNumber numberWithBool: YES] forKey: #"masterCheckbox"];
// now we expect the slave to be back on, since that was it's previous value
NSLog(#"slaveCheckbox value: %#", [myModelDictionary objectForKey: #"slaveCheckbox"]);
}
I implemented the block/KVO hook-up by creating an object to keep track of the blocks and userInfos, then have that be the KVO observer. Here's what I did:
#import <objc/runtime.h>
static void* kKVOBehaviorsKey = &kKVOBehaviorsKey;
#interface KBKVOBehaviorObserver : NSObject
{
NSMutableDictionary* mBehaviorsByKey;
NSMutableDictionary* mUserInfosByKey;
}
#end
#implementation KBKVOBehaviorObserver
- (id)init
{
if (self = [super init])
{
mBehaviorsByKey = [[NSMutableDictionary alloc] init];
mUserInfosByKey = [[NSMutableDictionary alloc] init];
}
return self;
}
- (void)dealloc
{
[mBehaviorsByKey release];
mBehaviorsByKey = nil;
[mUserInfosByKey release];
mUserInfosByKey = nil;
[super dealloc];
}
- (void)addBehavior: (KBBehavior)block forKeyPath: (NSString*)keyPath userInfo: (id)userInfo
{
#synchronized(self)
{
id copiedBlock = [[block copy] autorelease];
[mBehaviorsByKey setObject: copiedBlock forKey: keyPath];
[mUserInfosByKey setObject: userInfo forKey: keyPath];
}
}
- (void)removeBehaviorForKeyPath: (NSString*)keyPath
{
#synchronized(self)
{
[mUserInfosByKey removeObjectForKey: keyPath];
[mBehaviorsByKey removeObjectForKey: keyPath];
}
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if (context == kKVOBehaviorsKey)
{
KBBehavior behavior = nil;
id userInfo = nil;
#synchronized(self)
{
behavior = [[[mBehaviorsByKey objectForKey: keyPath] retain] autorelease];
userInfo = [[[mUserInfosByKey objectForKey: keyPath] retain] autorelease];
}
if (behavior)
{
id oldValue = [change objectForKey: NSKeyValueChangeOldKey];
id newValue = [change objectForKey: NSKeyValueChangeNewKey];
behavior(object, keyPath, oldValue, newValue, userInfo);
}
}
}
#end
#implementation NSObject (KBKVOBehaviorObserver)
- (void)addBehavior: (KBBehavior)block forKeyPath: (NSString*)keyPath options: (NSKeyValueObservingOptions)options userInfo: (id)userInfo
{
KBKVOBehaviorObserver* obs = nil;
#synchronized(self)
{
obs = objc_getAssociatedObject(self, kKVOBehaviorsKey);
if (nil == obs)
{
obs = [[[KBKVOBehaviorObserver alloc] init] autorelease];
objc_setAssociatedObject(self, kKVOBehaviorsKey, obs, OBJC_ASSOCIATION_RETAIN);
}
}
// Put the behavior and userInfos into stuff...
[obs addBehavior: block forKeyPath: keyPath userInfo: userInfo];
// add the observation
[self addObserver: obs forKeyPath: keyPath options: options context: kKVOBehaviorsKey];
}
- (void)removeBehaviorForKeyPath: (NSString*)keyPath
{
KBKVOBehaviorObserver* obs = nil;
obs = [[objc_getAssociatedObject(self, kKVOBehaviorsKey) retain] autorelease];
// Remove the observation
[self removeObserver: obs forKeyPath: keyPath context: kKVOBehaviorsKey];
// remove the behavior
[obs removeBehaviorForKeyPath: keyPath];
}
#end
One thing that's sort of unfortunate, is that you have to remove the observations/behaviors in order to break down the transitive retain cycle between the original dictionary and the observing object, so if you don't remove the behaviors, you'll leak the collection. But overall this pattern should be useful.
Hope this helps.
I am just grasping the concepts of TDD and mocking, and am running into an issue in terms of how to properly. I have a sheet that drops down and lets a user create a new core data object and save it to the data store. I am not sure if I am taking the best approach to testing it.
- (IBAction)add:(id)sender
{
NSString *itemName = [self.itemNameTextField stringValue];
SGItem *newItem = [NSEntityDescription insertNewObjectForEntityForName:kItemEntityName inManagedObjectContext:[self managedObjectContext]];
newItem.name = itemName;
NSError *error = nil;
BOOL canSaveNewItem = [[self managedObjectContext] save:&error];
if (!canSaveNewItem)
{
[NSApp presentError:error];
}
[self clearFormFields]; // Private method that clears text fields, disables buttons
[NSApp endSheet:[self window] returnCode:NSOKButton];
}
I'm trying to write two test methods to test this: one that tests the scenario where the managed object can't save and one where it successfully saves.
#interface SGAddItemWindowControllerTests : SGTestCase
{
#private
SGAddItemWindowController *addItemWindowController;
id mockApp;
id mockNameField;
}
- (void)setUp
{
mockNameField = [OCMockObject mockForClass:[NSTextField class]];
mockApp = [OCMockObject mockForClass:[NSApplication class]];
addItemWindowController = [[BLAddItemWindowController alloc] init];
[addItemWindowController setValue:mockNameField forKey:#"itemNameTextField"];
}
- (void)testAddingNewItemFromSheetFailed
{
// Setup
NSString *fakeName = #"";
[[[mockNameField expect] andReturn:fakeName] stringValue];
[[mockApp expect] presentError:[OCMArg any]];
// Execute
[addItemWindowController add:nil];
// Verify
[mockApp verify];
}
- (void)testAddingNewItemFromSheetSucceeds
{
// Setup
NSString *fakeName = #"Item Name";
[[[mockNameField expect] andReturn:fakeName] stringValue];
[[mockApp expect] endSheet:[OCMArg any] returnCode:NSOKButton];
// Execute
[addItemWindowController add:nil];
// Verify
[mockApp verify];
[mockNameField verify];
}
#end
Here are the issues I know I have, but am not sure how to work out:
I am not sure how to handle dealing with the managed object context in terms of the test. Should I bring up the entire core data stack or just create a mock of NSManagedObjectContext?
The idea of just setting the text field values as the way to trigger the if statement seems wrong. Ideally I think I should stub out the save: method and return YES or NO, but given question 1 I'm not sure about the Core Data aspects of it all.
I think I'm on the right track, but I could use a second opinion on how to tackle my issues and set me on the right path for testing the code snippet.
Justin,
What I do for question #1 is to create an actual NSManagedObjectContext but create an im-memory persistence store. Nothing hits the disk and I test the CoreData version of the truth.
I have a MWCoreDataTest class (extends in my case GTMTestCase) that builds the moc and initializes the persistence store
- (NSManagedObjectContext *) managedObjectContext {
if (managedObjectContext != nil) {
return managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
managedObjectContext = [[NSManagedObjectContext alloc] init];
[managedObjectContext setPersistentStoreCoordinator: coordinator];
}
return managedObjectContext;
}
- (NSPersistentStoreCoordinator*)persistentStoreCoordinator;
{
if (persistentStoreCoordinator) return persistentStoreCoordinator;
NSError* error = nil;
NSManagedObjectModel *mom = [self managedObjectModel];
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc]
initWithManagedObjectModel:mom];
if (![persistentStoreCoordinator addPersistentStoreWithType:NSInMemoryStoreType
configuration:nil
URL:nil
options:nil
error:&error]) {
[[NSApplication sharedApplication] presentError:error];
return nil;
}
return persistentStoreCoordinator;
}
WRT #2, I think that's ok - if you plan on testing more than one behavior in the class, move the
[addItemWindowController setValue:mockNameField forKey:#"itemNameTextField"];
to the testAdding.. method
If you solve #1, then you could just set the itemNameText field to nil and your save validation would trigger.
WRT #3, I would validate that building a mock on NSApp === building a mock on NSApplication
What is that you want to test? Do you want to test that Core Data does the saving or not? Or, do you want to test that your application responds correctly to the result of the call to CoreData?
Either way I think you should extract a method that performs the saving along the lines of:
-(BOOL)saveNewItem:(NSString *)itemName error:(NSError **)error {
SGItem *newItem = [NSEntityDescription insertNewObjectForEntityForName:kItemEntityName inManagedObjectContext:[self managedObjectContext]];
newItem.name = itemName;
NSError *error = nil;
return[[self managedObjectContext] save:&error];
}
- (IBAction)add:(id)sender {
NSString *itemName = [self.itemNameTextField stringValue];
NSError *error = nil;
BOOL canSaveNewItem = [self saveNewItem:itemName error:&error];
if (!canSaveNewItem) {
[NSApp presentError:error];
}
[self clearFormFields]; // Private method that clears text fields, disables buttons
[NSApp endSheet:[self window] returnCode:NSOKButton];
}
This way you can test that Core Data saving works as expected by settings up an in memory store and not have to care about the business logic. You should also be able to override or mock the result of this method for testing the business logic.
I would perhaps even move all the Core Data stuff to a separate class that would encapsulate the interaction for easier mocking.