diff --git a/Code/CoreData/CoreData.h b/Code/CoreData/CoreData.h index 592f8d7b0f..f1226d1f4f 100644 --- a/Code/CoreData/CoreData.h +++ b/Code/CoreData/CoreData.h @@ -23,6 +23,7 @@ #import "NSManagedObject+ActiveRecord.h" #import "RKManagedObjectStore.h" #import "RKManagedObjectSeeder.h" +#import "RKManagedObjectLoader.h" #import "RKManagedObjectMapping.h" #import "RKManagedObjectMappingOperation.h" #import "RKManagedObjectCaching.h" diff --git a/Code/CoreData/NSEntityDescription+RKAdditions.h b/Code/CoreData/NSEntityDescription+RKAdditions.h index 5da928b455..5a7b4a48fc 100644 --- a/Code/CoreData/NSEntityDescription+RKAdditions.h +++ b/Code/CoreData/NSEntityDescription+RKAdditions.h @@ -71,12 +71,12 @@ extern NSString * const RKEntityDescriptionPrimaryKeyAttributeValuePredicateSubs value. This predicate is constructed by evaluating the cached predicate returned by the predicateForPrimaryKeyAttribute with a dictionary of substitution variables specifying that $PRIMARY_KEY_VALUE is equal to the given value. - + **NOTE**: This method considers the type of the receiver's primary key attribute when constructing - the predicate. It will coerce the given value into either an NSString or an NSNumber as + the predicate. It will coerce the given value into either an NSString or an NSNumber as appropriate. This behavior is a convenience to avoid annoying issues related to Core Data's handling of predicates for NSString and NSNumber types that were not appropriately casted. - + @return A predicate speciying that the value of the primary key attribute is equal to a given value. */ - (NSPredicate *)predicateForPrimaryKeyAttributeWithValue:(id)value; @@ -84,9 +84,9 @@ extern NSString * const RKEntityDescriptionPrimaryKeyAttributeValuePredicateSubs /** Coerces the given value into the class representing the primary key. Currently support NSString and NSNumber coercsions. - + @bug **NOTE** This API is temporary and will be deprecated and replaced. - @since 0.10.1 + @since 0.10.1 */ - (id)coerceValueForPrimaryKey:(id)primaryKeyValue; diff --git a/Code/CoreData/NSEntityDescription+RKAdditions.m b/Code/CoreData/NSEntityDescription+RKAdditions.m index c244f4aeee..d8d9cc9ca8 100644 --- a/Code/CoreData/NSEntityDescription+RKAdditions.m +++ b/Code/CoreData/NSEntityDescription+RKAdditions.m @@ -38,14 +38,14 @@ - (Class)primaryKeyAttributeClass if (attributeDescription) { return NSClassFromString(attributeDescription.attributeValueClassName); } - + return nil; } - (NSString *)primaryKeyAttributeName { // Check for an associative object reference - NSString *primaryKeyAttribute = (NSString *) objc_getAssociatedObject(self, &primaryKeyAttributeNameKey); + NSString *primaryKeyAttribute = (NSString *)objc_getAssociatedObject(self, &primaryKeyAttributeNameKey); // Fall back to the userInfo dictionary if (! primaryKeyAttribute) { @@ -71,7 +71,7 @@ - (void)setPrimaryKeyAttributeName:(NSString *)primaryKeyAttributeName - (NSPredicate *)predicateForPrimaryKeyAttribute { - return (NSPredicate *) objc_getAssociatedObject(self, &primaryKeyPredicateKey); + return (NSPredicate *)objc_getAssociatedObject(self, &primaryKeyPredicateKey); } - (id)coerceValueForPrimaryKey:(id)primaryKeyValue @@ -92,7 +92,7 @@ - (id)coerceValueForPrimaryKey:(id)primaryKeyValue } } } - + return searchValue; } diff --git a/Code/CoreData/NSManagedObject+ActiveRecord.h b/Code/CoreData/NSManagedObject+ActiveRecord.h index 1d05f63e15..cf8936fa3e 100644 --- a/Code/CoreData/NSManagedObject+ActiveRecord.h +++ b/Code/CoreData/NSManagedObject+ActiveRecord.h @@ -31,59 +31,59 @@ * The NSEntityDescription for the Subclass * defaults to the subclass className, may be overridden */ -+ (NSEntityDescription*)entity; ++ (NSEntityDescription *)entity; /** * Returns an initialized NSFetchRequest for the entity, with no predicate */ -+ (NSFetchRequest*)fetchRequest; ++ (NSFetchRequest *)fetchRequest; /** * Fetches all objects from the persistent store identified by the fetchRequest */ -+ (NSArray*)objectsWithFetchRequest:(NSFetchRequest*)fetchRequest; ++ (NSArray *)objectsWithFetchRequest:(NSFetchRequest *)fetchRequest; /** * Retrieves the number of objects that would be retrieved by the fetchRequest, * if executed */ -+ (NSUInteger)countOfObjectsWithFetchRequest:(NSFetchRequest*)fetchRequest; ++ (NSUInteger)countOfObjectsWithFetchRequest:(NSFetchRequest *)fetchRequest; /** * Fetches all objects from the persistent store via a set of fetch requests and * returns all results in a single array. */ -+ (NSArray*)objectsWithFetchRequests:(NSArray*)fetchRequests; ++ (NSArray *)objectsWithFetchRequests:(NSArray *)fetchRequests; /** * Fetches the first object identified by the fetch request. A limit of one will be * applied to the fetch request before dispatching. */ -+ (id)objectWithFetchRequest:(NSFetchRequest*)fetchRequest; ++ (id)objectWithFetchRequest:(NSFetchRequest *)fetchRequest; /** * Fetches all objects from the persistent store by constructing a fetch request and * applying the predicate supplied. A short-cut for doing filtered searches on the objects * of this class under management. */ -+ (NSArray*)objectsWithPredicate:(NSPredicate*)predicate; ++ (NSArray *)objectsWithPredicate:(NSPredicate *)predicate; /** * Fetches the first object matching a predicate from the persistent store. A fetch request * will be constructed for you and a fetch limit of 1 will be applied. */ -+ (id)objectWithPredicate:(NSPredicate*)predicate; ++ (id)objectWithPredicate:(NSPredicate *)predicate; /** * Fetches all managed objects of this class from the persistent store as an array */ -+ (NSArray*)allObjects; ++ (NSArray *)allObjects; /** * Returns a count of all managed objects of this class in the persistent store. On * error, will populate the error argument */ -+ (NSUInteger)count:(NSError**)error; ++ (NSUInteger)count:(NSError **)error; /** * Returns a count of all managed objects of this class in the persistent store. Deprecated @@ -124,7 +124,7 @@ //////////////////////////////////////////////////////////////////////////////////////////////////// -+ (NSManagedObjectContext*)currentContext; ++ (NSManagedObjectContext *)currentContext; + (void)handleErrors:(NSError *)error; @@ -152,8 +152,8 @@ + (NSNumber *)numberOfEntitiesWithPredicate:(NSPredicate *)searchTerm; + (NSNumber *)numberOfEntitiesWithPredicate:(NSPredicate *)searchTerm inContext:(NSManagedObjectContext *)context; -+ (BOOL) hasAtLeastOneEntity; -+ (BOOL) hasAtLeastOneEntityInContext:(NSManagedObjectContext *)context; ++ (BOOL)hasAtLeastOneEntity; ++ (BOOL)hasAtLeastOneEntityInContext:(NSManagedObjectContext *)context; + (NSFetchRequest *)requestAll; + (NSFetchRequest *)requestAllInContext:(NSManagedObjectContext *)context; @@ -180,8 +180,8 @@ + (NSArray *)findAllWithPredicate:(NSPredicate *)searchTerm inContext:(NSManagedObjectContext *)context; + (NSNumber *)maxValueFor:(NSString *)property; -+ (id) objectWithMinValueFor:(NSString *)property; -+ (id) objectWithMinValueFor:(NSString *)property inContext:(NSManagedObjectContext *)context; ++ (id)objectWithMinValueFor:(NSString *)property; ++ (id)objectWithMinValueFor:(NSString *)property inContext:(NSManagedObjectContext *)context; + (id)findFirst; + (id)findFirstInContext:(NSManagedObjectContext *)context; diff --git a/Code/CoreData/NSManagedObject+ActiveRecord.m b/Code/CoreData/NSManagedObject+ActiveRecord.m index a246f020ee..41163f53fe 100644 --- a/Code/CoreData/NSManagedObject+ActiveRecord.m +++ b/Code/CoreData/NSManagedObject+ActiveRecord.m @@ -28,17 +28,20 @@ @implementation NSManagedObjectContext (ActiveRecord) -+ (NSManagedObjectContext *)defaultContext { ++ (NSManagedObjectContext *)defaultContext +{ return defaultContext; } -+ (void)setDefaultContext:(NSManagedObjectContext *)newDefaultContext { ++ (void)setDefaultContext:(NSManagedObjectContext *)newDefaultContext +{ [newDefaultContext retain]; [defaultContext release]; defaultContext = newDefaultContext; } -+ (NSManagedObjectContext *)contextForCurrentThread { ++ (NSManagedObjectContext *)contextForCurrentThread +{ NSAssert([RKManagedObjectStore defaultObjectStore], @"[RKManagedObjectStore defaultObjectStore] cannot be nil"); return [[RKManagedObjectStore defaultObjectStore] managedObjectContextForCurrentThread]; } @@ -51,29 +54,33 @@ @implementation NSManagedObject (ActiveRecord) #pragma mark - RKManagedObject methods -+ (NSEntityDescription*)entity { - NSString* className = [NSString stringWithCString:class_getName([self class]) encoding:NSASCIIStringEncoding]; ++ (NSEntityDescription *)entity +{ + NSString *className = [NSString stringWithCString:class_getName([self class]) encoding:NSASCIIStringEncoding]; return [NSEntityDescription entityForName:className inManagedObjectContext:[NSManagedObjectContext contextForCurrentThread]]; } -+ (NSFetchRequest*)fetchRequest { ++ (NSFetchRequest *)fetchRequest +{ NSFetchRequest *fetchRequest = [[[NSFetchRequest alloc] init] autorelease]; NSEntityDescription *entity = [self entity]; [fetchRequest setEntity:entity]; return fetchRequest; } -+ (NSArray*)objectsWithFetchRequest:(NSFetchRequest*)fetchRequest { - NSError* error = nil; - NSArray* objects = [[NSManagedObjectContext contextForCurrentThread] executeFetchRequest:fetchRequest error:&error]; ++ (NSArray *)objectsWithFetchRequest:(NSFetchRequest *)fetchRequest +{ + NSError *error = nil; + NSArray *objects = [[NSManagedObjectContext contextForCurrentThread] executeFetchRequest:fetchRequest error:&error]; if (objects == nil) { RKLogError(@"Error: %@", [error localizedDescription]); } return objects; } -+ (NSUInteger)countOfObjectsWithFetchRequest:(NSFetchRequest*)fetchRequest { - NSError* error = nil; ++ (NSUInteger)countOfObjectsWithFetchRequest:(NSFetchRequest *)fetchRequest +{ + NSError *error = nil; NSUInteger objectCount = [[NSManagedObjectContext contextForCurrentThread] countForFetchRequest:fetchRequest error:&error]; if (objectCount == NSNotFound) { RKLogError(@"Error: %@", [error localizedDescription]); @@ -81,19 +88,21 @@ + (NSUInteger)countOfObjectsWithFetchRequest:(NSFetchRequest*)fetchRequest { return objectCount; } -+ (NSArray*)objectsWithFetchRequests:(NSArray*)fetchRequests { - NSMutableArray* mutableObjectArray = [[NSMutableArray alloc] init]; - for (NSFetchRequest* fetchRequest in fetchRequests) { ++ (NSArray *)objectsWithFetchRequests:(NSArray *)fetchRequests +{ + NSMutableArray *mutableObjectArray = [[NSMutableArray alloc] init]; + for (NSFetchRequest *fetchRequest in fetchRequests) { [mutableObjectArray addObjectsFromArray:[self objectsWithFetchRequest:fetchRequest]]; } - NSArray* objects = [NSArray arrayWithArray:mutableObjectArray]; + NSArray *objects = [NSArray arrayWithArray:mutableObjectArray]; [mutableObjectArray release]; return objects; } -+ (id)objectWithFetchRequest:(NSFetchRequest*)fetchRequest { ++ (id)objectWithFetchRequest:(NSFetchRequest *)fetchRequest +{ [fetchRequest setFetchLimit:1]; - NSArray* objects = [self objectsWithFetchRequest:fetchRequest]; + NSArray *objects = [self objectsWithFetchRequest:fetchRequest]; if ([objects count] == 0) { return nil; } else { @@ -101,59 +110,69 @@ + (id)objectWithFetchRequest:(NSFetchRequest*)fetchRequest { } } -+ (NSArray*)objectsWithPredicate:(NSPredicate*)predicate { - NSFetchRequest* fetchRequest = [self fetchRequest]; ++ (NSArray *)objectsWithPredicate:(NSPredicate *)predicate +{ + NSFetchRequest *fetchRequest = [self fetchRequest]; [fetchRequest setPredicate:predicate]; return [self objectsWithFetchRequest:fetchRequest]; } -+ (id)objectWithPredicate:(NSPredicate*)predicate { - NSFetchRequest* fetchRequest = [self fetchRequest]; ++ (id)objectWithPredicate:(NSPredicate *)predicate +{ + NSFetchRequest *fetchRequest = [self fetchRequest]; [fetchRequest setPredicate:predicate]; return [self objectWithFetchRequest:fetchRequest]; } -+ (NSArray*)allObjects { ++ (NSArray *)allObjects +{ return [self objectsWithPredicate:nil]; } -+ (NSUInteger)count:(NSError**)error { - NSFetchRequest* fetchRequest = [self fetchRequest]; ++ (NSUInteger)count:(NSError **)error +{ + NSFetchRequest *fetchRequest = [self fetchRequest]; return [[NSManagedObjectContext contextForCurrentThread] countForFetchRequest:fetchRequest error:error]; } -+ (NSUInteger)count { ++ (NSUInteger)count +{ NSError *error = nil; return [self count:&error]; } -+ (id)object { ++ (id)object +{ id object = [[self alloc] initWithEntity:[self entity] insertIntoManagedObjectContext:[NSManagedObjectContext contextForCurrentThread]]; return [object autorelease]; } -- (BOOL)isNew { +- (BOOL)isNew +{ NSDictionary *vals = [self committedValuesForKeys:nil]; return [vals count] == 0; } -+ (id)findByPrimaryKey:(id)primaryKeyValue inContext:(NSManagedObjectContext *)context { ++ (id)findByPrimaryKey:(id)primaryKeyValue inContext:(NSManagedObjectContext *)context +{ NSPredicate *predicate = [[self entityDescriptionInContext:context] predicateForPrimaryKeyAttributeWithValue:primaryKeyValue]; if (! predicate) { RKLogWarning(@"Attempt to findByPrimaryKey for entity with nil primaryKeyAttribute. Set the primaryKeyAttributeName and try again! %@", self); return nil; } - + return [self findFirstWithPredicate:predicate inContext:context]; } -+ (id)findByPrimaryKey:(id)primaryKeyValue { ++ (id)findByPrimaryKey:(id)primaryKeyValue +{ return [self findByPrimaryKey:primaryKeyValue inContext:[NSManagedObjectContext contextForCurrentThread]]; } #pragma mark - MagicalRecord Ported Methods -+ (NSManagedObjectContext*)currentContext; { ++ (NSManagedObjectContext *)currentContext; +{ return [NSManagedObjectContext contextForCurrentThread]; } @@ -276,7 +295,7 @@ + (NSArray *)propertiesNamed:(NSArray *)properties } else { - RKLogError(@"Property '%@' not found in %@ properties for %@", propertyName, [propDict count], NSStringFromClass(self)); + RKLogError(@"Property '%@' not found in %d properties for %@", propertyName, [propDict count], NSStringFromClass(self)); } } } @@ -292,7 +311,7 @@ + (NSArray *)sortAscending:(BOOL)ascending attributes:(id)attributesToSortBy, .. id attributeName; va_list variadicArguments; va_start(variadicArguments, attributesToSortBy); - while ((attributeName = va_arg(variadicArguments, id))!= nil) + while ((attributeName = va_arg(variadicArguments, id)) != nil) { NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:attributeName ascending:ascending]; [attributes addObject:sortDescriptor]; @@ -305,7 +324,7 @@ + (NSArray *)sortAscending:(BOOL)ascending attributes:(id)attributesToSortBy, .. { va_list variadicArguments; va_start(variadicArguments, attributesToSortBy); - [attributes addObject:[[[NSSortDescriptor alloc] initWithKey:attributesToSortBy ascending:ascending] autorelease] ]; + [attributes addObject:[[[NSSortDescriptor alloc] initWithKey:attributesToSortBy ascending:ascending] autorelease]]; va_end(variadicArguments); } @@ -457,7 +476,7 @@ + (NSFetchRequest *)requestAllSortedBy:(NSString *)sortTerm ascending:(BOOL)asce [request setIncludesSubentities:NO]; [request setFetchBatchSize:[self defaultBatchSize]]; - if (sortTerm != nil){ + if (sortTerm != nil) { NSSortDescriptor *sortBy = [[NSSortDescriptor alloc] initWithKey:sortTerm ascending:ascending]; [request setSortDescriptors:[NSArray arrayWithObject:sortBy]]; [sortBy release]; diff --git a/Code/CoreData/NSManagedObjectContext+RKAdditions.m b/Code/CoreData/NSManagedObjectContext+RKAdditions.m index f838cd1db4..81bffff567 100644 --- a/Code/CoreData/NSManagedObjectContext+RKAdditions.m +++ b/Code/CoreData/NSManagedObjectContext+RKAdditions.m @@ -15,7 +15,7 @@ @implementation NSManagedObjectContext (RKAdditions) - (RKManagedObjectStore *)managedObjectStore { - return (RKManagedObjectStore *) objc_getAssociatedObject(self, &NSManagedObject_RKManagedObjectStoreAssociatedKey); + return (RKManagedObjectStore *)objc_getAssociatedObject(self, &NSManagedObject_RKManagedObjectStoreAssociatedKey); } - (void)setManagedObjectStore:(RKManagedObjectStore *)managedObjectStore diff --git a/Code/CoreData/RKEntityByAttributeCache.m b/Code/CoreData/RKEntityByAttributeCache.m index 4a64204c04..6aac3590b9 100644 --- a/Code/CoreData/RKEntityByAttributeCache.m +++ b/Code/CoreData/RKEntityByAttributeCache.m @@ -147,7 +147,8 @@ - (NSManagedObject *)objectWithAttributeValue:(id)attributeValue return ([objects count] > 0) ? [objects objectAtIndex:0] : nil; } -- (NSManagedObject *)objectWithID:(NSManagedObjectID *)objectID { +- (NSManagedObject *)objectWithID:(NSManagedObjectID *)objectID +{ /* NOTE: We use existingObjectWithID: as opposed to objectWithID: as objectWithID: can return us a fault diff --git a/Code/CoreData/RKInMemoryManagedObjectCache.m b/Code/CoreData/RKInMemoryManagedObjectCache.m index 01d5932629..e73f590d23 100644 --- a/Code/CoreData/RKInMemoryManagedObjectCache.m +++ b/Code/CoreData/RKInMemoryManagedObjectCache.m @@ -50,7 +50,7 @@ - (NSManagedObject *)findInstanceOfEntity:(NSEntityDescription *)entity RKLogInfo(@"Caching instances of Entity '%@' by primary key attribute '%@'", entity.name, primaryKeyAttribute); [entityCache cacheObjectsForEntity:entity byAttribute:primaryKeyAttribute]; RKEntityByAttributeCache *attributeCache = [entityCache attributeCacheForEntity:entity attribute:primaryKeyAttribute]; - RKLogTrace(@"Cached %ld objects", (long) [attributeCache count]); + RKLogTrace(@"Cached %ld objects", (long)[attributeCache count]); } return [entityCache objectForEntity:entity withAttribute:primaryKeyAttribute value:primaryKeyValue]; diff --git a/Code/CoreData/RKManagedObjectLoader.h b/Code/CoreData/RKManagedObjectLoader.h index 5a8d46e290..dbd410e428 100644 --- a/Code/CoreData/RKManagedObjectLoader.h +++ b/Code/CoreData/RKManagedObjectLoader.h @@ -28,9 +28,8 @@ concerns imposed by Core Data. */ @interface RKManagedObjectLoader : RKObjectLoader { - RKManagedObjectStore *_objectStore; - NSManagedObjectID* _targetObjectID; - NSMutableSet* _managedObjectKeyPaths; + NSManagedObjectID *_targetObjectID; + NSMutableSet *_managedObjectKeyPaths; BOOL _deleteObjectOnFailure; } @@ -39,7 +38,7 @@ @see RKManagedObjectStore */ -@property (nonatomic, retain) RKManagedObjectStore* objectStore; +@property (nonatomic, retain) RKManagedObjectStore *objectStore; + (id)loaderWithURL:(RKURL *)URL mappingProvider:(RKObjectMappingProvider *)mappingProvider objectStore:(RKManagedObjectStore *)objectStore; - (id)initWithURL:(RKURL *)URL mappingProvider:(RKObjectMappingProvider *)mappingProvider objectStore:(RKManagedObjectStore *)objectStore; diff --git a/Code/CoreData/RKManagedObjectLoader.m b/Code/CoreData/RKManagedObjectLoader.m index bc65db0752..bbdb097948 100644 --- a/Code/CoreData/RKManagedObjectLoader.m +++ b/Code/CoreData/RKManagedObjectLoader.m @@ -37,11 +37,13 @@ @implementation RKManagedObjectLoader @synthesize objectStore = _objectStore; -+ (id)loaderWithURL:(RKURL *)URL mappingProvider:(RKObjectMappingProvider *)mappingProvider objectStore:(RKManagedObjectStore *)objectStore { ++ (id)loaderWithURL:(RKURL *)URL mappingProvider:(RKObjectMappingProvider *)mappingProvider objectStore:(RKManagedObjectStore *)objectStore +{ return [[[self alloc] initWithURL:URL mappingProvider:mappingProvider objectStore:objectStore] autorelease]; } -- (id)initWithURL:(RKURL *)URL mappingProvider:(RKObjectMappingProvider *)mappingProvider objectStore:(RKManagedObjectStore *)objectStore { +- (id)initWithURL:(RKURL *)URL mappingProvider:(RKObjectMappingProvider *)mappingProvider objectStore:(RKManagedObjectStore *)objectStore +{ self = [self initWithURL:URL mappingProvider:mappingProvider]; if (self) { _objectStore = [objectStore retain]; @@ -50,7 +52,8 @@ - (id)initWithURL:(RKURL *)URL mappingProvider:(RKObjectMappingProvider *)mappin return self; } -- (id)initWithURL:(RKURL *)URL mappingProvider:(RKObjectMappingProvider *)mappingProvider { +- (id)initWithURL:(RKURL *)URL mappingProvider:(RKObjectMappingProvider *)mappingProvider +{ self = [super initWithURL:URL mappingProvider:mappingProvider]; if (self) { _managedObjectKeyPaths = [[NSMutableSet alloc] init]; @@ -59,7 +62,8 @@ - (id)initWithURL:(RKURL *)URL mappingProvider:(RKObjectMappingProvider *)mappin return self; } -- (void)dealloc { +- (void)dealloc +{ [_targetObjectID release]; _targetObjectID = nil; _deleteObjectOnFailure = NO; @@ -69,7 +73,8 @@ - (void)dealloc { [super dealloc]; } -- (void)reset { +- (void)reset +{ [super reset]; [_targetObjectID release]; _targetObjectID = nil; @@ -77,7 +82,8 @@ - (void)reset { #pragma mark - RKObjectMapperDelegate methods -- (void)objectMapper:(RKObjectMapper*)objectMapper didMapFromObject:(id)sourceObject toObject:(id)destinationObject atKeyPath:(NSString*)keyPath usingMapping:(RKObjectMapping*)objectMapping { +- (void)objectMapper:(RKObjectMapper *)objectMapper didMapFromObject:(id)sourceObject toObject:(id)destinationObject atKeyPath:(NSString *)keyPath usingMapping:(RKObjectMapping *)objectMapping +{ if ([destinationObject isKindOfClass:[NSManagedObject class]]) { [_managedObjectKeyPaths addObject:keyPath]; } @@ -86,7 +92,8 @@ - (void)objectMapper:(RKObjectMapper*)objectMapper didMapFromObject:(id)sourceOb #pragma mark - RKObjectLoader overrides // Overload the target object reader to return a thread-local copy of the target object -- (id)targetObject { +- (id)targetObject +{ if ([NSThread isMainThread] == NO && _targetObjectID) { return [self.objectStore objectWithID:_targetObjectID]; } @@ -94,7 +101,8 @@ - (id)targetObject { return _targetObject; } -- (void)setTargetObject:(NSObject*)targetObject { +- (void)setTargetObject:(NSObject *)targetObject +{ [_targetObject release]; _targetObject = nil; _targetObject = [targetObject retain]; @@ -103,24 +111,24 @@ - (void)setTargetObject:(NSObject*)targetObject { _targetObjectID = nil; } -- (BOOL)prepareURLRequest { - // TODO: Can we just do this if the object hasn't been saved already??? - +- (BOOL)prepareURLRequest +{ // NOTE: There is an important sequencing issue here. You MUST save the // managed object context before retaining the objectID or you will run // into an error where the object context cannot be saved. We do this // right before send to avoid sequencing issues where the target object is // set before the managed object store. if (self.targetObject && [self.targetObject isKindOfClass:[NSManagedObject class]]) { - _deleteObjectOnFailure = [(NSManagedObject*)self.targetObject isNew]; + _deleteObjectOnFailure = [(NSManagedObject *)self.targetObject isNew]; [self.objectStore save:nil]; - _targetObjectID = [[(NSManagedObject*)self.targetObject objectID] retain]; + _targetObjectID = [[(NSManagedObject *)self.targetObject objectID] retain]; } return [super prepareURLRequest]; } -- (NSArray *)cachedObjects { +- (NSArray *)cachedObjects +{ NSFetchRequest *fetchRequest = [self.mappingProvider fetchRequestForResourcePath:self.resourcePath]; if (fetchRequest) { return [NSManagedObject objectsWithFetchRequest:fetchRequest]; @@ -129,7 +137,8 @@ - (NSArray *)cachedObjects { return nil; } -- (void)deleteCachedObjectsMissingFromResult:(RKObjectMappingResult*)result { +- (void)deleteCachedObjectsMissingFromResult:(RKObjectMappingResult *)result +{ if (! [self isGET]) { RKLogDebug(@"Skipping cleanup of objects via managed object cache: only used for GET requests."); return; @@ -150,10 +159,11 @@ - (void)deleteCachedObjectsMissingFromResult:(RKObjectMappingResult*)result { } // NOTE: We are on the background thread here, be mindful of Core Data's threading needs -- (void)processMappingResult:(RKObjectMappingResult*)result { +- (void)processMappingResult:(RKObjectMappingResult *)result +{ NSAssert(_sentSynchronously || ![NSThread isMainThread], @"Mapping result processing should occur on a background thread"); if (_targetObjectID && self.targetObject && self.method == RKRequestMethodDELETE) { - NSManagedObject* backgroundThreadObject = [self.objectStore objectWithID:_targetObjectID]; + NSManagedObject *backgroundThreadObject = [self.objectStore objectWithID:_targetObjectID]; RKLogInfo(@"Deleting local object %@ due to DELETE request", backgroundThreadObject); [[self.objectStore managedObjectContextForCurrentThread] deleteObject:backgroundThreadObject]; } @@ -165,8 +175,8 @@ - (void)processMappingResult:(RKObjectMappingResult*)result { BOOL success = [self.objectStore save:&error]; if (! success) { RKLogError(@"Failed to save managed object context after mapping completed: %@", [error localizedDescription]); - NSMethodSignature* signature = [(NSObject *)self methodSignatureForSelector:@selector(informDelegateOfError:)]; - RKManagedObjectThreadSafeInvocation* invocation = [RKManagedObjectThreadSafeInvocation invocationWithMethodSignature:signature]; + NSMethodSignature *signature = [(NSObject *)self methodSignatureForSelector:@selector(informDelegateOfError:)]; + RKManagedObjectThreadSafeInvocation *invocation = [RKManagedObjectThreadSafeInvocation invocationWithMethodSignature:signature]; [invocation setTarget:self]; [invocation setSelector:@selector(informDelegateOfError:)]; [invocation setArgument:&error atIndex:2]; @@ -179,9 +189,9 @@ - (void)processMappingResult:(RKObjectMappingResult*)result { } } - NSDictionary* dictionary = [result asDictionary]; - NSMethodSignature* signature = [self methodSignatureForSelector:@selector(informDelegateOfObjectLoadWithResultDictionary:)]; - RKManagedObjectThreadSafeInvocation* invocation = [RKManagedObjectThreadSafeInvocation invocationWithMethodSignature:signature]; + NSDictionary *dictionary = [result asDictionary]; + NSMethodSignature *signature = [self methodSignatureForSelector:@selector(informDelegateOfObjectLoadWithResultDictionary:)]; + RKManagedObjectThreadSafeInvocation *invocation = [RKManagedObjectThreadSafeInvocation invocationWithMethodSignature:signature]; [invocation setObjectStore:self.objectStore]; [invocation setTarget:self]; [invocation setSelector:@selector(informDelegateOfObjectLoadWithResultDictionary:)]; @@ -191,13 +201,14 @@ - (void)processMappingResult:(RKObjectMappingResult*)result { } // Overloaded to handle deleting an object orphaned by a failed postObject: -- (void)handleResponseError { +- (void)handleResponseError +{ [super handleResponseError]; if (_targetObjectID) { if (_deleteObjectOnFailure) { RKLogInfo(@"Error response encountered: Deleting existing managed object with ID: %@", _targetObjectID); - NSManagedObject* objectToDelete = [self.objectStore objectWithID:_targetObjectID]; + NSManagedObject *objectToDelete = [self.objectStore objectWithID:_targetObjectID]; if (objectToDelete) { [[self.objectStore managedObjectContextForCurrentThread] deleteObject:objectToDelete]; [self.objectStore save:nil]; @@ -210,9 +221,10 @@ - (void)handleResponseError { } } -- (BOOL)isResponseMappable { +- (BOOL)isResponseMappable +{ if ([self.response wasLoadedFromCache]) { - NSArray* cachedObjects = [self cachedObjects]; + NSArray *cachedObjects = [self cachedObjects]; if (! cachedObjects) { RKLogDebug(@"Skipping managed object mapping optimization -> Managed object cache returned nil cachedObjects for resourcePath: %@", self.resourcePath); return [super isResponseMappable]; diff --git a/Code/CoreData/RKManagedObjectMapping.h b/Code/CoreData/RKManagedObjectMapping.h index 876ab23c9f..dbf2749fde 100644 --- a/Code/CoreData/RKManagedObjectMapping.h +++ b/Code/CoreData/RKManagedObjectMapping.h @@ -29,8 +29,6 @@ entity. */ @interface RKManagedObjectMapping : RKObjectMapping { - NSEntityDescription *_entity; - NSString *_primaryKeyAttribute; NSMutableDictionary *_relationshipToPrimaryKeyMappings; } diff --git a/Code/CoreData/RKManagedObjectMapping.m b/Code/CoreData/RKManagedObjectMapping.m index 8008218f90..44392719af 100644 --- a/Code/CoreData/RKManagedObjectMapping.m +++ b/Code/CoreData/RKManagedObjectMapping.m @@ -36,26 +36,31 @@ @implementation RKManagedObjectMapping @synthesize primaryKeyAttribute = _primaryKeyAttribute; @synthesize objectStore = _objectStore; -+ (id)mappingForClass:(Class)objectClass { ++ (id)mappingForClass:(Class)objectClass +{ @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"You must provide a managedObjectStore. Invoke mappingForClass:inManagedObjectStore: instead."] userInfo:nil]; } -+ (id)mappingForClass:(Class)objectClass inManagedObjectStore:(RKManagedObjectStore *)objectStore { ++ (id)mappingForClass:(Class)objectClass inManagedObjectStore:(RKManagedObjectStore *)objectStore +{ return [self mappingForEntityWithName:NSStringFromClass(objectClass) inManagedObjectStore:objectStore]; } -+ (RKManagedObjectMapping *)mappingForEntity:(NSEntityDescription*)entity inManagedObjectStore:(RKManagedObjectStore *)objectStore { ++ (RKManagedObjectMapping *)mappingForEntity:(NSEntityDescription *)entity inManagedObjectStore:(RKManagedObjectStore *)objectStore +{ return [[[self alloc] initWithEntity:entity inManagedObjectStore:objectStore] autorelease]; } -+ (RKManagedObjectMapping *)mappingForEntityWithName:(NSString*)entityName inManagedObjectStore:(RKManagedObjectStore *)objectStore { ++ (RKManagedObjectMapping *)mappingForEntityWithName:(NSString *)entityName inManagedObjectStore:(RKManagedObjectStore *)objectStore +{ return [self mappingForEntity:[NSEntityDescription entityForName:entityName inManagedObjectContext:objectStore.primaryManagedObjectContext] inManagedObjectStore:objectStore]; } -- (id)initWithEntity:(NSEntityDescription*)entity inManagedObjectStore:(RKManagedObjectStore*)objectStore { +- (id)initWithEntity:(NSEntityDescription *)entity inManagedObjectStore:(RKManagedObjectStore *)objectStore +{ NSAssert(entity, @"Cannot initialize an RKManagedObjectMapping without an entity. Maybe you want RKObjectMapping instead?"); NSAssert(objectStore, @"Object store cannot be nil"); Class objectClass = NSClassFromString([entity managedObjectClassName]); @@ -73,7 +78,8 @@ - (id)initWithEntity:(NSEntityDescription*)entity inManagedObjectStore:(RKManage return self; } -- (id)init { +- (id)init +{ self = [super init]; if (self) { _relationshipToPrimaryKeyMappings = [[NSMutableDictionary alloc] init]; @@ -82,7 +88,8 @@ - (id)init { return self; } -- (void)dealloc { +- (void)dealloc +{ [self removeObserver:self forKeyPath:@"entity"]; [self removeObserver:self forKeyPath:@"primaryKeyAttribute"]; @@ -91,20 +98,23 @@ - (void)dealloc { [super dealloc]; } -- (NSDictionary*)relationshipsAndPrimaryKeyAttributes { +- (NSDictionary *)relationshipsAndPrimaryKeyAttributes +{ return _relationshipToPrimaryKeyMappings; } -- (void)connectRelationship:(NSString*)relationshipName withObjectForPrimaryKeyAttribute:(NSString*)primaryKeyAttribute { +- (void)connectRelationship:(NSString *)relationshipName withObjectForPrimaryKeyAttribute:(NSString *)primaryKeyAttribute +{ NSAssert([_relationshipToPrimaryKeyMappings objectForKey:relationshipName] == nil, @"Cannot add connect relationship %@ by primary key, a mapping already exists.", relationshipName); [_relationshipToPrimaryKeyMappings setObject:primaryKeyAttribute forKey:relationshipName]; } -- (void)connectRelationshipsWithObjectsForPrimaryKeyAttributes:(NSString*)firstRelationshipName, ... { +- (void)connectRelationshipsWithObjectsForPrimaryKeyAttributes:(NSString *)firstRelationshipName, ... +{ va_list args; va_start(args, firstRelationshipName); - for (NSString* relationshipName = firstRelationshipName; relationshipName != nil; relationshipName = va_arg(args, NSString*)) { - NSString* primaryKeyAttribute = va_arg(args, NSString*); + for (NSString *relationshipName = firstRelationshipName; relationshipName != nil; relationshipName = va_arg(args, NSString *)) { + NSString *primaryKeyAttribute = va_arg(args, NSString *); NSAssert(primaryKeyAttribute != nil, @"Cannot connect a relationship without an attribute containing the primary key"); [self connectRelationship:relationshipName withObjectForPrimaryKeyAttribute:primaryKeyAttribute]; // TODO: Raise proper exception here, argument error... @@ -112,40 +122,44 @@ - (void)connectRelationshipsWithObjectsForPrimaryKeyAttributes:(NSString*)firstR va_end(args); } -- (void)connectRelationship:(NSString*)relationshipName withObjectForPrimaryKeyAttribute:(NSString*)primaryKeyAttribute whenValueOfKeyPath:(NSString*)keyPath isEqualTo:(id)value { +- (void)connectRelationship:(NSString *)relationshipName withObjectForPrimaryKeyAttribute:(NSString *)primaryKeyAttribute whenValueOfKeyPath:(NSString *)keyPath isEqualTo:(id)value +{ NSAssert([_relationshipToPrimaryKeyMappings objectForKey:relationshipName] == nil, @"Cannot add connect relationship %@ by primary key, a mapping already exists.", relationshipName); - RKDynamicObjectMappingMatcher* matcher = [[RKDynamicObjectMappingMatcher alloc] initWithKey:keyPath value:value primaryKeyAttribute:primaryKeyAttribute]; + RKDynamicObjectMappingMatcher *matcher = [[RKDynamicObjectMappingMatcher alloc] initWithKey:keyPath value:value primaryKeyAttribute:primaryKeyAttribute]; [_relationshipToPrimaryKeyMappings setObject:matcher forKey:relationshipName]; [matcher release]; } -- (void)connectRelationship:(NSString*)relationshipName withObjectForPrimaryKeyAttribute:(NSString*)primaryKeyAttribute usingEvaluationBlock:(BOOL (^)(id data))block { +- (void)connectRelationship:(NSString *)relationshipName withObjectForPrimaryKeyAttribute:(NSString *)primaryKeyAttribute usingEvaluationBlock:(BOOL (^)(id data))block +{ NSAssert([_relationshipToPrimaryKeyMappings objectForKey:relationshipName] == nil, @"Cannot add connect relationship %@ by primary key, a mapping already exists.", relationshipName); - RKDynamicObjectMappingMatcher* matcher = [[RKDynamicObjectMappingMatcher alloc] initWithPrimaryKeyAttribute:primaryKeyAttribute evaluationBlock:block]; + RKDynamicObjectMappingMatcher *matcher = [[RKDynamicObjectMappingMatcher alloc] initWithPrimaryKeyAttribute:primaryKeyAttribute evaluationBlock:block]; [_relationshipToPrimaryKeyMappings setObject:matcher forKey:relationshipName]; [matcher release]; } -- (id)defaultValueForMissingAttribute:(NSString*)attributeName { +- (id)defaultValueForMissingAttribute:(NSString *)attributeName +{ NSAttributeDescription *desc = [[self.entity attributesByName] valueForKey:attributeName]; return [desc defaultValue]; } -- (id)mappableObjectForData:(id)mappableData { +- (id)mappableObjectForData:(id)mappableData +{ NSAssert(mappableData, @"Mappable data cannot be nil"); id object = nil; id primaryKeyValue = nil; - NSString* primaryKeyAttribute; + NSString *primaryKeyAttribute; - NSEntityDescription* entity = [self entity]; - RKObjectAttributeMapping* primaryKeyAttributeMapping = nil; + NSEntityDescription *entity = [self entity]; + RKObjectAttributeMapping *primaryKeyAttributeMapping = nil; primaryKeyAttribute = [self primaryKeyAttribute]; if (primaryKeyAttribute) { // If a primary key has been set on the object mapping, find the attribute mapping // so that we can extract any existing primary key from the mappable data - for (RKObjectAttributeMapping* attributeMapping in self.attributeMappings) { + for (RKObjectAttributeMapping *attributeMapping in self.attributeMappings) { if ([attributeMapping.destinationKeyPath isEqualToString:primaryKeyAttribute]) { primaryKeyAttributeMapping = attributeMapping; break; @@ -157,7 +171,7 @@ - (id)mappableObjectForData:(id)mappableData { RKLogDebug(@"Detected use of nested dictionary key as primaryKey attribute..."); primaryKeyValue = [[mappableData allKeys] lastObject]; } else { - NSString* keyPathForPrimaryKeyElement = primaryKeyAttributeMapping.sourceKeyPath; + NSString *keyPathForPrimaryKeyElement = primaryKeyAttributeMapping.sourceKeyPath; if (keyPathForPrimaryKeyElement) { primaryKeyValue = [mappableData valueForKeyPath:keyPathForPrimaryKeyElement]; } else { @@ -193,7 +207,8 @@ - (id)mappableObjectForData:(id)mappableData { return object; } -- (Class)classForProperty:(NSString*)propertyName { +- (Class)classForProperty:(NSString *)propertyName +{ Class propertyClass = [super classForProperty:propertyName]; if (! propertyClass) { propertyClass = [[RKObjectPropertyInspector sharedInspector] typeForProperty:propertyName ofEntity:self.entity]; diff --git a/Code/CoreData/RKManagedObjectMappingOperation.m b/Code/CoreData/RKManagedObjectMappingOperation.m index 4d52293e6b..265d98bfbe 100644 --- a/Code/CoreData/RKManagedObjectMappingOperation.m +++ b/Code/CoreData/RKManagedObjectMappingOperation.m @@ -32,13 +32,14 @@ @implementation RKManagedObjectMappingOperation -- (void)connectRelationship:(NSString *)relationshipName { - NSDictionary* relationshipsAndPrimaryKeyAttributes = [(RKManagedObjectMapping*)self.objectMapping relationshipsAndPrimaryKeyAttributes]; +- (void)connectRelationship:(NSString *)relationshipName +{ + NSDictionary *relationshipsAndPrimaryKeyAttributes = [(RKManagedObjectMapping *)self.objectMapping relationshipsAndPrimaryKeyAttributes]; id primaryKeyObject = [relationshipsAndPrimaryKeyAttributes objectForKey:relationshipName]; - NSString* primaryKeyAttribute = nil; + NSString *primaryKeyAttribute = nil; if ([primaryKeyObject isKindOfClass:[RKDynamicObjectMappingMatcher class]]) { RKLogTrace(@"Found a dynamic matcher attempting to connect relationshipName: %@", relationshipName); - RKDynamicObjectMappingMatcher* matcher = (RKDynamicObjectMappingMatcher*)primaryKeyObject; + RKDynamicObjectMappingMatcher *matcher = (RKDynamicObjectMappingMatcher *)primaryKeyObject; if ([matcher isMatchForData:self.destinationObject]) { primaryKeyAttribute = matcher.primaryKeyAttribute; RKLogTrace(@"Dynamic matched succeeded. Proceeding to connect relationshipName '%@' using primaryKeyAttribute '%@'", relationshipName, primaryKeyAttribute); @@ -47,22 +48,22 @@ - (void)connectRelationship:(NSString *)relationshipName { return; } } else if ([primaryKeyObject isKindOfClass:[NSString class]]) { - primaryKeyAttribute = (NSString*)primaryKeyObject; + primaryKeyAttribute = (NSString *)primaryKeyObject; } NSAssert(primaryKeyAttribute, @"Cannot connect relationship without primaryKeyAttribute"); - RKObjectRelationshipMapping* relationshipMapping = [self.objectMapping mappingForRelationship:relationshipName]; + RKObjectRelationshipMapping *relationshipMapping = [self.objectMapping mappingForRelationship:relationshipName]; RKObjectMappingDefinition *mapping = relationshipMapping.mapping; - NSAssert(mapping, @"Attempted to connect relationship for keyPath '%@' without a relationship mapping defined."); + NSAssert(mapping, @"Attempted to connect relationship for keyPath '%@' without a relationship mapping defined.", relationshipName); if (! [mapping isKindOfClass:[RKObjectMapping class]]) { RKLogWarning(@"Can only connect relationships for RKObjectMapping relationships. Found %@: Skipping...", NSStringFromClass([mapping class])); return; } - RKManagedObjectMapping *objectMapping = (RKManagedObjectMapping *) mapping; + RKManagedObjectMapping *objectMapping = (RKManagedObjectMapping *)mapping; NSAssert(relationshipMapping, @"Unable to find relationship mapping '%@' to connect by primaryKey", relationshipName); NSAssert([relationshipMapping isKindOfClass:[RKObjectRelationshipMapping class]], @"Expected mapping for %@ to be a relationship mapping", relationshipName); NSAssert([relationshipMapping.mapping isKindOfClass:[RKManagedObjectMapping class]], @"Can only connect RKManagedObjectMapping relationships"); - NSString* primaryKeyAttributeOfRelatedObject = [(RKManagedObjectMapping*)objectMapping primaryKeyAttribute]; + NSString *primaryKeyAttributeOfRelatedObject = [(RKManagedObjectMapping *)objectMapping primaryKeyAttribute]; NSAssert(primaryKeyAttributeOfRelatedObject, @"Cannot connect relationship: mapping for %@ has no primary key attribute specified", NSStringFromClass(objectMapping.objectClass)); id valueOfLocalPrimaryKeyAttribute = [self.destinationObject valueForKey:primaryKeyAttribute]; if (valueOfLocalPrimaryKeyAttribute) { @@ -72,9 +73,9 @@ - (void)connectRelationship:(NSString *)relationshipName { // Implemented for issue 284 - https://github.com/RestKit/RestKit/issues/284 relatedObject = [NSMutableSet set]; - NSObject *cache = [[(RKManagedObjectMapping*)[self objectMapping] objectStore] cacheStrategy]; + NSObject *cache = [[(RKManagedObjectMapping *)[self objectMapping] objectStore] cacheStrategy]; for (id foreignKey in valueOfLocalPrimaryKeyAttribute) { - id searchResult = [cache findInstanceOfEntity:objectMapping.entity withPrimaryKeyAttribute:primaryKeyAttributeOfRelatedObject value:foreignKey inManagedObjectContext:[[(RKManagedObjectMapping*)[self objectMapping] objectStore] managedObjectContextForCurrentThread]]; + id searchResult = [cache findInstanceOfEntity:objectMapping.entity withPrimaryKeyAttribute:primaryKeyAttributeOfRelatedObject value:foreignKey inManagedObjectContext:[[(RKManagedObjectMapping *)[self objectMapping] objectStore] managedObjectContextForCurrentThread]]; if (searchResult) { [relatedObject addObject:searchResult]; } @@ -83,7 +84,7 @@ - (void)connectRelationship:(NSString *)relationshipName { RKLogTrace(@"Connecting has-one relationship at keyPath '%@' to object with primaryKey attribute '%@'", relationshipName, primaryKeyAttributeOfRelatedObject); // Normal foreign key - NSObject *cache = [[(RKManagedObjectMapping*)[self objectMapping] objectStore] cacheStrategy]; + NSObject *cache = [[(RKManagedObjectMapping *)[self objectMapping] objectStore] cacheStrategy]; relatedObject = [cache findInstanceOfEntity:objectMapping.entity withPrimaryKeyAttribute:primaryKeyAttributeOfRelatedObject value:valueOfLocalPrimaryKeyAttribute inManagedObjectContext:[self.destinationObject managedObjectContext]]; } if (relatedObject) { @@ -102,10 +103,11 @@ - (void)connectRelationship:(NSString *)relationshipName { } } -- (void)connectRelationships { - NSDictionary* relationshipsAndPrimaryKeyAttributes = [(RKManagedObjectMapping *)self.objectMapping relationshipsAndPrimaryKeyAttributes]; +- (void)connectRelationships +{ + NSDictionary *relationshipsAndPrimaryKeyAttributes = [(RKManagedObjectMapping *)self.objectMapping relationshipsAndPrimaryKeyAttributes]; RKLogTrace(@"relationshipsAndPrimaryKeyAttributes: %@", relationshipsAndPrimaryKeyAttributes); - for (NSString* relationshipName in relationshipsAndPrimaryKeyAttributes) { + for (NSString *relationshipName in relationshipsAndPrimaryKeyAttributes) { if (self.queue) { RKLogTrace(@"Enqueueing relationship connection using operation queue"); __block RKManagedObjectMappingOperation *selfRef = self; @@ -118,7 +120,8 @@ - (void)connectRelationships { } } -- (BOOL)performMapping:(NSError **)error { +- (BOOL)performMapping:(NSError **)error +{ BOOL success = [super performMapping:error]; if ([self.objectMapping isKindOfClass:[RKManagedObjectMapping class]]) { /** diff --git a/Code/CoreData/RKManagedObjectSearchEngine.h b/Code/CoreData/RKManagedObjectSearchEngine.h index 64abcf570e..e230b665cf 100644 --- a/Code/CoreData/RKManagedObjectSearchEngine.h +++ b/Code/CoreData/RKManagedObjectSearchEngine.h @@ -20,9 +20,7 @@ #import "RKSearchEngine.h" -@interface RKManagedObjectSearchEngine : NSObject { - RKSearchMode _mode; -} +@interface RKManagedObjectSearchEngine : NSObject /** * The type of searching to perform. Can be either RKSearchModeAnd or RKSearchModeOr. @@ -40,12 +38,12 @@ * Normalize and tokenize the provided string into an NSArray. * Note that returned value may contain entries of empty strings. */ -+ (NSArray*)tokenizedNormalizedString:(NSString*)string; ++ (NSArray *)tokenizedNormalizedString:(NSString *)string; /** * Generate a predicate for the supplied search term against * searchableAttributes (defined for an RKSearchableManagedObject) */ -- (NSPredicate*)predicateForSearch:(NSString*)searchText; +- (NSPredicate *)predicateForSearch:(NSString *)searchText; @end diff --git a/Code/CoreData/RKManagedObjectSearchEngine.m b/Code/CoreData/RKManagedObjectSearchEngine.m index 0740d99bc7..2acb1c32d9 100644 --- a/Code/CoreData/RKManagedObjectSearchEngine.m +++ b/Code/CoreData/RKManagedObjectSearchEngine.m @@ -28,16 +28,18 @@ @implementation RKManagedObjectSearchEngine -static NSMutableCharacterSet* __removeSet; +static NSMutableCharacterSet *__removeSet; @synthesize mode = _mode; -+ (id)searchEngine { - RKManagedObjectSearchEngine* searchEngine = [[[RKManagedObjectSearchEngine alloc] init] autorelease]; ++ (id)searchEngine +{ + RKManagedObjectSearchEngine *searchEngine = [[[RKManagedObjectSearchEngine alloc] init] autorelease]; return searchEngine; } -- (id)init { +- (id)init +{ if (self = [super init]) { _mode = RKSearchModeOr; } @@ -48,9 +50,10 @@ - (id)init { #pragma mark - #pragma mark Private -- (NSPredicate*)predicateForSearch:(NSArray*)searchTerms compoundSelector:(SEL)selector { - NSMutableArray* termPredicates = [NSMutableArray array]; - for (NSString* searchTerm in searchTerms) { +- (NSPredicate *)predicateForSearch:(NSArray *)searchTerms compoundSelector:(SEL)selector +{ + NSMutableArray *termPredicates = [NSMutableArray array]; + for (NSString *searchTerm in searchTerms) { [termPredicates addObject: [NSPredicate predicateWithFormat:@"(ANY searchWords.word beginswith %@)", searchTerm]]; } @@ -60,26 +63,28 @@ - (NSPredicate*)predicateForSearch:(NSArray*)searchTerms compoundSelector:(SEL)s #pragma mark - #pragma mark Public -+ (NSArray*)tokenizedNormalizedString:(NSString*)string { ++ (NSArray *)tokenizedNormalizedString:(NSString *)string +{ if (__removeSet == nil) { - NSMutableCharacterSet* removeSet = [[NSCharacterSet alphanumericCharacterSet] mutableCopy]; + NSMutableCharacterSet *removeSet = [[NSCharacterSet alphanumericCharacterSet] mutableCopy]; [removeSet formUnionWithCharacterSet:[NSCharacterSet whitespaceCharacterSet]]; [removeSet invert]; __removeSet = removeSet; } - NSString* scannerString = [[[[string lowercaseString] decomposedStringWithCanonicalMapping] + NSString *scannerString = [[[[string lowercaseString] decomposedStringWithCanonicalMapping] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] stringByReplacingOccurrencesOfString:@"-" withString:@" "]; - NSArray* tokens = [[[scannerString componentsSeparatedByCharactersInSet:__removeSet] + NSArray *tokens = [[[scannerString componentsSeparatedByCharactersInSet:__removeSet] componentsJoinedByString:@""] componentsSeparatedByString:@" "]; return tokens; } -- (NSPredicate*)predicateForSearch:(NSString*)searchText { - NSString* searchQuery = [searchText copy]; - NSArray* searchTerms = [RKManagedObjectSearchEngine tokenizedNormalizedString:searchQuery]; +- (NSPredicate *)predicateForSearch:(NSString *)searchText +{ + NSString *searchQuery = [searchText copy]; + NSArray *searchTerms = [RKManagedObjectSearchEngine tokenizedNormalizedString:searchQuery]; [searchQuery release]; if ([searchTerms count] == 0) { diff --git a/Code/CoreData/RKManagedObjectSeeder.h b/Code/CoreData/RKManagedObjectSeeder.h index c856a81ce6..07fe53e86b 100644 --- a/Code/CoreData/RKManagedObjectSeeder.h +++ b/Code/CoreData/RKManagedObjectSeeder.h @@ -21,13 +21,13 @@ #import "ObjectMapping.h" // The default seed database filename. Used when the object store has not been initialized -extern NSString* const RKDefaultSeedDatabaseFileName; +extern NSString * const RKDefaultSeedDatabaseFileName; @protocol RKManagedObjectSeederDelegate @required // Invoked when the seeder creates a new object -- (void)didSeedObject:(NSManagedObject*)object fromFile:(NSString*)fileName; +- (void)didSeedObject:(NSManagedObject *)object fromFile:(NSString *)fileName; @end /** @@ -39,36 +39,35 @@ extern NSString* const RKDefaultSeedDatabaseFileName; * data immediately available for use within Core Data. */ @interface RKManagedObjectSeeder : NSObject { - RKObjectManager* _manager; - NSObject* _delegate; + RKObjectManager *_manager; } // Delegate for seeding operations -@property (nonatomic, assign) NSObject* delegate; +@property (nonatomic, assign) NSObject *delegate; // Path to the generated seed database on disk -@property (nonatomic, readonly) NSString* pathToSeedDatabase; +@property (nonatomic, readonly) NSString *pathToSeedDatabase; /** * Generates a seed database using an object manager and a null terminated list of files. Exits * the seeding process and outputs an informational message */ -+ (void)generateSeedDatabaseWithObjectManager:(RKObjectManager*)objectManager fromFiles:(NSString*)fileName, ...; ++ (void)generateSeedDatabaseWithObjectManager:(RKObjectManager *)objectManager fromFiles:(NSString *)fileName, ...; /** * Returns an object seeder ready to begin seeding. Requires a fully configured instance of an object manager. */ -+ (RKManagedObjectSeeder*)objectSeederWithObjectManager:(RKObjectManager*)objectManager; ++ (RKManagedObjectSeeder *)objectSeederWithObjectManager:(RKObjectManager *)objectManager; /** * Seed the database with objects from the specified file(s). The list must be terminated by nil */ -- (void)seedObjectsFromFiles:(NSString*)fileName, ...; +- (void)seedObjectsFromFiles:(NSString *)fileName, ...; /** * Seed the database with objects from the specified file using the supplied object mapping. */ -- (void)seedObjectsFromFile:(NSString*)fileName withObjectMapping:(RKObjectMapping*)nilOrObjectMapping; +- (void)seedObjectsFromFile:(NSString *)fileName withObjectMapping:(RKObjectMapping *)nilOrObjectMapping; /** * Seed the database with objects from the specified file, from the specified bundle, using the supplied object mapping. diff --git a/Code/CoreData/RKManagedObjectSeeder.m b/Code/CoreData/RKManagedObjectSeeder.m index f779984f41..3b23cdd7f4 100644 --- a/Code/CoreData/RKManagedObjectSeeder.m +++ b/Code/CoreData/RKManagedObjectSeeder.m @@ -32,40 +32,43 @@ #define RKLogComponent lcl_cRestKitCoreData @interface RKManagedObjectSeeder (Private) -- (id)initWithObjectManager:(RKObjectManager*)manager; -- (void)seedObjectsFromFileNames:(NSArray*)fileNames; +- (id)initWithObjectManager:(RKObjectManager *)manager; +- (void)seedObjectsFromFileNames:(NSArray *)fileNames; @end -NSString* const RKDefaultSeedDatabaseFileName = @"RKSeedDatabase.sqlite"; +NSString * const RKDefaultSeedDatabaseFileName = @"RKSeedDatabase.sqlite"; @implementation RKManagedObjectSeeder @synthesize delegate = _delegate; -+ (void)generateSeedDatabaseWithObjectManager:(RKObjectManager*)objectManager fromFiles:(NSString*)firstFileName, ... { - RKManagedObjectSeeder* seeder = [RKManagedObjectSeeder objectSeederWithObjectManager:objectManager]; ++ (void)generateSeedDatabaseWithObjectManager:(RKObjectManager *)objectManager fromFiles:(NSString *)firstFileName, ... +{ + RKManagedObjectSeeder *seeder = [RKManagedObjectSeeder objectSeederWithObjectManager:objectManager]; va_list args; va_start(args, firstFileName); - NSMutableArray* fileNames = [NSMutableArray array]; - for (NSString* fileName = firstFileName; fileName != nil; fileName = va_arg(args, id)) { + NSMutableArray *fileNames = [NSMutableArray array]; + for (NSString *fileName = firstFileName; fileName != nil; fileName = va_arg(args, id)) { [fileNames addObject:fileName]; } va_end(args); // Seed the files - for (NSString* fileName in fileNames) { + for (NSString *fileName in fileNames) { [seeder seedObjectsFromFile:fileName withObjectMapping:nil]; } [seeder finalizeSeedingAndExit]; } -+ (RKManagedObjectSeeder*)objectSeederWithObjectManager:(RKObjectManager*)objectManager { ++ (RKManagedObjectSeeder *)objectSeederWithObjectManager:(RKObjectManager *)objectManager +{ return [[[RKManagedObjectSeeder alloc] initWithObjectManager:objectManager] autorelease]; } -- (id)initWithObjectManager:(RKObjectManager*)manager { +- (id)initWithObjectManager:(RKObjectManager *)manager +{ self = [self init]; if (self) { _manager = [manager retain]; @@ -82,46 +85,50 @@ - (id)initWithObjectManager:(RKObjectManager*)manager { return self; } -- (void)dealloc { +- (void)dealloc +{ [_manager release]; [super dealloc]; } -- (NSString*)pathToSeedDatabase { +- (NSString *)pathToSeedDatabase +{ return _manager.objectStore.pathToStoreFile; } -- (void)seedObjectsFromFiles:(NSString*)firstFileName, ... { +- (void)seedObjectsFromFiles:(NSString *)firstFileName, ... +{ va_list args; va_start(args, firstFileName); - NSMutableArray* fileNames = [NSMutableArray array]; - for (NSString* fileName = firstFileName; fileName != nil; fileName = va_arg(args, id)) { + NSMutableArray *fileNames = [NSMutableArray array]; + for (NSString *fileName = firstFileName; fileName != nil; fileName = va_arg(args, id)) { [fileNames addObject:fileName]; } va_end(args); - for (NSString* fileName in fileNames) { + for (NSString *fileName in fileNames) { [self seedObjectsFromFile:fileName withObjectMapping:nil]; } } -- (void)seedObjectsFromFile:(NSString*)fileName withObjectMapping:(RKObjectMapping *)nilOrObjectMapping { +- (void)seedObjectsFromFile:(NSString *)fileName withObjectMapping:(RKObjectMapping *)nilOrObjectMapping +{ [self seedObjectsFromFile:fileName withObjectMapping:nilOrObjectMapping bundle:nil]; } - (void)seedObjectsFromFile:(NSString *)fileName withObjectMapping:(RKObjectMapping *)nilOrObjectMapping bundle:(NSBundle *)nilOrBundle { - NSError* error = nil; + NSError *error = nil; if (nilOrBundle == nil) { nilOrBundle = [NSBundle mainBundle]; } - NSString* filePath = [nilOrBundle pathForResource:fileName ofType:nil]; - NSString* payload = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error]; + NSString *filePath = [nilOrBundle pathForResource:fileName ofType:nil]; + NSString *payload = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error]; if (payload) { - NSString* MIMEType = [fileName MIMETypeForPathExtension]; + NSString *MIMEType = [fileName MIMETypeForPathExtension]; if (MIMEType == nil) { // Default the MIME type to the value of the Accept header if we couldn't detect it... MIMEType = _manager.acceptMIMEType; @@ -131,7 +138,7 @@ - (void)seedObjectsFromFile:(NSString *)fileName withObjectMapping:(RKObjectMapp id parsedData = [parser objectFromString:payload error:&error]; NSAssert(parsedData, @"Cannot perform object load without data for mapping"); - RKObjectMappingProvider* mappingProvider = nil; + RKObjectMappingProvider *mappingProvider = nil; if (nilOrObjectMapping) { mappingProvider = [[RKObjectMappingProvider new] autorelease]; [mappingProvider setMapping:nilOrObjectMapping forKeyPath:@""]; @@ -139,40 +146,41 @@ - (void)seedObjectsFromFile:(NSString *)fileName withObjectMapping:(RKObjectMapp mappingProvider = _manager.mappingProvider; } - RKObjectMapper* mapper = [RKObjectMapper mapperWithObject:parsedData mappingProvider:mappingProvider]; - RKObjectMappingResult* result = [mapper performMapping]; + RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:parsedData mappingProvider:mappingProvider]; + RKObjectMappingResult *result = [mapper performMapping]; if (result == nil) { RKLogError(@"Database seeding from file '%@' failed due to object mapping errors: %@", fileName, mapper.errors); return; } - NSArray* mappedObjects = [result asCollection]; + NSArray *mappedObjects = [result asCollection]; NSAssert1([mappedObjects isKindOfClass:[NSArray class]], @"Expected an NSArray of objects, got %@", mappedObjects); // Inform the delegate if (self.delegate) { - for (NSManagedObject* object in mappedObjects) { + for (NSManagedObject *object in mappedObjects) { [self.delegate didSeedObject:object fromFile:fileName]; } } - RKLogInfo(@"Seeded %lu objects from %@...", (unsigned long) [mappedObjects count], [NSString stringWithFormat:@"%@", fileName]); + RKLogInfo(@"Seeded %lu objects from %@...", (unsigned long)[mappedObjects count], [NSString stringWithFormat:@"%@", fileName]); } else { RKLogError(@"Unable to read file %@: %@", fileName, [error localizedDescription]); } } -- (void)finalizeSeedingAndExit { +- (void)finalizeSeedingAndExit +{ NSError *error = nil; BOOL success = [[_manager objectStore] save:&error]; if (! success) { RKLogError(@"[RestKit] RKManagedObjectSeeder: Error saving object context: %@", [error localizedDescription]); } - NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); - NSString* basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil; - NSString* storeFileName = [[_manager objectStore] storeFilename]; - NSString* destinationPath = [basePath stringByAppendingPathComponent:storeFileName]; + NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); + NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil; + NSString *storeFileName = [[_manager objectStore] storeFilename]; + NSString *destinationPath = [basePath stringByAppendingPathComponent:storeFileName]; RKLogInfo(@"A seeded database has been generated at '%@'. " @"Please execute `open \"%@\"` in your Terminal and copy %@ to your app. Be sure to add the seed database to your \"Copy Resources\" build phase.", destinationPath, basePath, storeFileName); diff --git a/Code/CoreData/RKManagedObjectStore.h b/Code/CoreData/RKManagedObjectStore.h index 75bfd8e64f..4b67414a0b 100644 --- a/Code/CoreData/RKManagedObjectStore.h +++ b/Code/CoreData/RKManagedObjectStore.h @@ -27,7 +27,7 @@ /** * Notifications */ -extern NSString* const RKManagedObjectStoreDidFailSaveNotification; +extern NSString * const RKManagedObjectStoreDidFailSaveNotification; /////////////////////////////////////////////////////////////////// @@ -46,26 +46,20 @@ extern NSString* const RKManagedObjectStoreDidFailSaveNotification; /////////////////////////////////////////////////////////////////// -@interface RKManagedObjectStore : NSObject { - NSObject* _delegate; - NSString* _storeFilename; - NSString* _pathToStoreFile; - NSManagedObjectModel* _managedObjectModel; - NSPersistentStoreCoordinator* _persistentStoreCoordinator; -} +@interface RKManagedObjectStore : NSObject // The delegate for this object store -@property (nonatomic, assign) NSObject* delegate; +@property (nonatomic, assign) NSObject *delegate; // The filename of the database backing this object store -@property (nonatomic, readonly) NSString* storeFilename; +@property (nonatomic, readonly) NSString *storeFilename; // The full path to the database backing this object store -@property (nonatomic, readonly) NSString* pathToStoreFile; +@property (nonatomic, readonly) NSString *pathToStoreFile; // Core Data -@property (nonatomic, readonly) NSManagedObjectModel* managedObjectModel; -@property (nonatomic, readonly) NSPersistentStoreCoordinator* persistentStoreCoordinator; +@property (nonatomic, readonly) NSManagedObjectModel *managedObjectModel; +@property (nonatomic, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator; ///----------------------------------------------------------------------------- /// @name Accessing the Default Object Store @@ -105,7 +99,7 @@ extern NSString* const RKManagedObjectStoreDidFailSaveNotification; /** * Initialize a new managed object store with a SQLite database with the filename specified */ -+ (RKManagedObjectStore*)objectStoreWithStoreFilename:(NSString*)storeFilename; ++ (RKManagedObjectStore *)objectStoreWithStoreFilename:(NSString *)storeFilename; /** * Initialize a new managed object store backed by a SQLite database with the specified filename. @@ -113,7 +107,7 @@ extern NSString* const RKManagedObjectStoreDidFailSaveNotification; * copying the seed database from the main bundle. If the managed object model provided is nil, * all models will be merged from the main bundle for you. */ -+ (RKManagedObjectStore*)objectStoreWithStoreFilename:(NSString *)storeFilename usingSeedDatabaseName:(NSString *)nilOrNameOfSeedDatabaseInMainBundle managedObjectModel:(NSManagedObjectModel*)nilOrManagedObjectModel delegate:(id)delegate; ++ (RKManagedObjectStore *)objectStoreWithStoreFilename:(NSString *)storeFilename usingSeedDatabaseName:(NSString *)nilOrNameOfSeedDatabaseInMainBundle managedObjectModel:(NSManagedObjectModel *)nilOrManagedObjectModel delegate:(id)delegate; /** * Initialize a new managed object store backed by a SQLite database with the specified filename, @@ -122,13 +116,13 @@ extern NSString* const RKManagedObjectStoreDidFailSaveNotification; * the store by copying the seed database from the main bundle. If the managed object model * provided is nil, all models will be merged from the main bundle for you. */ -+ (RKManagedObjectStore*)objectStoreWithStoreFilename:(NSString *)storeFilename inDirectory:(NSString *)directory usingSeedDatabaseName:(NSString *)nilOrNameOfSeedDatabaseInMainBundle managedObjectModel:(NSManagedObjectModel*)nilOrManagedObjectModel delegate:(id)delegate; ++ (RKManagedObjectStore *)objectStoreWithStoreFilename:(NSString *)storeFilename inDirectory:(NSString *)directory usingSeedDatabaseName:(NSString *)nilOrNameOfSeedDatabaseInMainBundle managedObjectModel:(NSManagedObjectModel *)nilOrManagedObjectModel delegate:(id)delegate; /** * Initialize a new managed object store with a SQLite database with the filename specified * @deprecated */ -- (id)initWithStoreFilename:(NSString*)storeFilename DEPRECATED_ATTRIBUTE; +- (id)initWithStoreFilename:(NSString *)storeFilename DEPRECATED_ATTRIBUTE; /** * Save the current contents of the managed object store @@ -145,13 +139,13 @@ extern NSString* const RKManagedObjectStoreDidFailSaveNotification; /** * Retrieves a model object from the appropriate context using the objectId */ -- (NSManagedObject*)objectWithID:(NSManagedObjectID*)objectID; +- (NSManagedObject *)objectWithID:(NSManagedObjectID *)objectID; /** * Retrieves a array of model objects from the appropriate context using * an array of NSManagedObjectIDs */ -- (NSArray*)objectsWithIDs:(NSArray*)objectIDs; +- (NSArray *)objectsWithIDs:(NSArray *)objectIDs; ///----------------------------------------------------------------------------- /// @name Retrieving Managed Object Contexts diff --git a/Code/CoreData/RKManagedObjectStore.m b/Code/CoreData/RKManagedObjectStore.m index fcc614ceb0..ff8afafeb0 100644 --- a/Code/CoreData/RKManagedObjectStore.m +++ b/Code/CoreData/RKManagedObjectStore.m @@ -35,19 +35,19 @@ #undef RKLogComponent #define RKLogComponent lcl_cRestKitCoreData -NSString* const RKManagedObjectStoreDidFailSaveNotification = @"RKManagedObjectStoreDidFailSaveNotification"; -static NSString* const RKManagedObjectStoreThreadDictionaryContextKey = @"RKManagedObjectStoreThreadDictionaryContextKey"; -static NSString* const RKManagedObjectStoreThreadDictionaryEntityCacheKey = @"RKManagedObjectStoreThreadDictionaryEntityCacheKey"; +NSString * const RKManagedObjectStoreDidFailSaveNotification = @"RKManagedObjectStoreDidFailSaveNotification"; +static NSString * const RKManagedObjectStoreThreadDictionaryContextKey = @"RKManagedObjectStoreThreadDictionaryContextKey"; +static NSString * const RKManagedObjectStoreThreadDictionaryEntityCacheKey = @"RKManagedObjectStoreThreadDictionaryEntityCacheKey"; static RKManagedObjectStore *defaultObjectStore = nil; @interface RKManagedObjectStore () @property (nonatomic, retain, readwrite) NSManagedObjectContext *primaryManagedObjectContext; -- (id)initWithStoreFilename:(NSString *)storeFilename inDirectory:(NSString *)nilOrDirectoryPath usingSeedDatabaseName:(NSString *)nilOrNameOfSeedDatabaseInMainBundle managedObjectModel:(NSManagedObjectModel*)nilOrManagedObjectModel delegate:(id)delegate; +- (id)initWithStoreFilename:(NSString *)storeFilename inDirectory:(NSString *)nilOrDirectoryPath usingSeedDatabaseName:(NSString *)nilOrNameOfSeedDatabaseInMainBundle managedObjectModel:(NSManagedObjectModel *)nilOrManagedObjectModel delegate:(id)delegate; - (void)createPersistentStoreCoordinator; -- (void)createStoreIfNecessaryUsingSeedDatabase:(NSString*)seedDatabase; -- (NSManagedObjectContext*)newManagedObjectContext; +- (void)createStoreIfNecessaryUsingSeedDatabase:(NSString *)seedDatabase; +- (NSManagedObjectContext *)newManagedObjectContext; @end @implementation RKManagedObjectStore @@ -60,11 +60,13 @@ @implementation RKManagedObjectStore @synthesize cacheStrategy = _cacheStrategy; @synthesize primaryManagedObjectContext; -+ (RKManagedObjectStore *)defaultObjectStore { ++ (RKManagedObjectStore *)defaultObjectStore +{ return defaultObjectStore; } -+ (void)setDefaultObjectStore:(RKManagedObjectStore *)objectStore { ++ (void)setDefaultObjectStore:(RKManagedObjectStore *)objectStore +{ [objectStore retain]; [defaultObjectStore release]; defaultObjectStore = objectStore; @@ -74,8 +76,8 @@ + (void)setDefaultObjectStore:(RKManagedObjectStore *)objectStore { + (void)deleteStoreAtPath:(NSString *)path { - NSURL* storeURL = [NSURL fileURLWithPath:path]; - NSError* error = nil; + NSURL *storeURL = [NSURL fileURLWithPath:path]; + NSError *error = nil; if ([[NSFileManager defaultManager] fileExistsAtPath:storeURL.path]) { if (! [[NSFileManager defaultManager] removeItemAtPath:storeURL.path error:&error]) { NSAssert(NO, @"Managed object store failed to delete persistent store : %@", error); @@ -91,23 +93,28 @@ + (void)deleteStoreInApplicationDataDirectoryWithFilename:(NSString *)filename [self deleteStoreAtPath:path]; } -+ (RKManagedObjectStore*)objectStoreWithStoreFilename:(NSString*)storeFilename { ++ (RKManagedObjectStore *)objectStoreWithStoreFilename:(NSString *)storeFilename +{ return [self objectStoreWithStoreFilename:storeFilename usingSeedDatabaseName:nil managedObjectModel:nil delegate:nil]; } -+ (RKManagedObjectStore*)objectStoreWithStoreFilename:(NSString *)storeFilename usingSeedDatabaseName:(NSString *)nilOrNameOfSeedDatabaseInMainBundle managedObjectModel:(NSManagedObjectModel*)nilOrManagedObjectModel delegate:(id)delegate { ++ (RKManagedObjectStore *)objectStoreWithStoreFilename:(NSString *)storeFilename usingSeedDatabaseName:(NSString *)nilOrNameOfSeedDatabaseInMainBundle managedObjectModel:(NSManagedObjectModel *)nilOrManagedObjectModel delegate:(id)delegate +{ return [[[self alloc] initWithStoreFilename:storeFilename inDirectory:nil usingSeedDatabaseName:nilOrNameOfSeedDatabaseInMainBundle managedObjectModel:nilOrManagedObjectModel delegate:delegate] autorelease]; } -+ (RKManagedObjectStore*)objectStoreWithStoreFilename:(NSString *)storeFilename inDirectory:(NSString *)directory usingSeedDatabaseName:(NSString *)nilOrNameOfSeedDatabaseInMainBundle managedObjectModel:(NSManagedObjectModel*)nilOrManagedObjectModel delegate:(id)delegate { ++ (RKManagedObjectStore *)objectStoreWithStoreFilename:(NSString *)storeFilename inDirectory:(NSString *)directory usingSeedDatabaseName:(NSString *)nilOrNameOfSeedDatabaseInMainBundle managedObjectModel:(NSManagedObjectModel *)nilOrManagedObjectModel delegate:(id)delegate +{ return [[[self alloc] initWithStoreFilename:storeFilename inDirectory:directory usingSeedDatabaseName:nilOrNameOfSeedDatabaseInMainBundle managedObjectModel:nilOrManagedObjectModel delegate:delegate] autorelease]; } -- (id)initWithStoreFilename:(NSString*)storeFilename { +- (id)initWithStoreFilename:(NSString *)storeFilename +{ return [self initWithStoreFilename:storeFilename inDirectory:nil usingSeedDatabaseName:nil managedObjectModel:nil delegate:nil]; } -- (id)initWithStoreFilename:(NSString *)storeFilename inDirectory:(NSString *)nilOrDirectoryPath usingSeedDatabaseName:(NSString *)nilOrNameOfSeedDatabaseInMainBundle managedObjectModel:(NSManagedObjectModel*)nilOrManagedObjectModel delegate:(id)delegate { +- (id)initWithStoreFilename:(NSString *)storeFilename inDirectory:(NSString *)nilOrDirectoryPath usingSeedDatabaseName:(NSString *)nilOrNameOfSeedDatabaseInMainBundle managedObjectModel:(NSManagedObjectModel *)nilOrManagedObjectModel delegate:(id)delegate +{ self = [self init]; if (self) { _storeFilename = [storeFilename retain]; @@ -127,7 +134,7 @@ - (id)initWithStoreFilename:(NSString *)storeFilename inDirectory:(NSString *)ni // NOTE: allBundles permits Core Data setup in unit tests nilOrManagedObjectModel = [NSManagedObjectModel mergedModelFromBundles:[NSBundle allBundles]]; } - NSMutableArray* allManagedObjectModels = [NSMutableArray arrayWithObject:nilOrManagedObjectModel]; + NSMutableArray *allManagedObjectModels = [NSMutableArray arrayWithObject:nilOrManagedObjectModel]; _managedObjectModel = [[NSManagedObjectModel modelByMergingModels:allManagedObjectModels] retain]; _delegate = delegate; @@ -154,8 +161,9 @@ - (id)initWithStoreFilename:(NSString *)storeFilename inDirectory:(NSString *)ni return self; } -- (void)setThreadLocalObject:(id)value forKey:(id)key { - NSMutableDictionary* threadDictionary = [[NSThread currentThread] threadDictionary]; +- (void)setThreadLocalObject:(id)value forKey:(id)key +{ + NSMutableDictionary *threadDictionary = [[NSThread currentThread] threadDictionary]; NSString *objectStoreKey = [NSString stringWithFormat:@"RKManagedObjectStore_%p", self]; if (! [threadDictionary valueForKey:objectStoreKey]) { [threadDictionary setValue:[NSMutableDictionary dictionary] forKey:objectStoreKey]; @@ -164,8 +172,9 @@ - (void)setThreadLocalObject:(id)value forKey:(id)key { [[threadDictionary objectForKey:objectStoreKey] setObject:value forKey:key]; } -- (id)threadLocalObjectForKey:(id)key { - NSMutableDictionary* threadDictionary = [[NSThread currentThread] threadDictionary]; +- (id)threadLocalObjectForKey:(id)key +{ + NSMutableDictionary *threadDictionary = [[NSThread currentThread] threadDictionary]; NSString *objectStoreKey = [NSString stringWithFormat:@"RKManagedObjectStore_%p", self]; if (! [threadDictionary valueForKey:objectStoreKey]) { [threadDictionary setObject:[NSMutableDictionary dictionary] forKey:objectStoreKey]; @@ -174,8 +183,9 @@ - (id)threadLocalObjectForKey:(id)key { return [[threadDictionary objectForKey:objectStoreKey] objectForKey:key]; } -- (void)removeThreadLocalObjectForKey:(id)key { - NSMutableDictionary* threadDictionary = [[NSThread currentThread] threadDictionary]; +- (void)removeThreadLocalObjectForKey:(id)key +{ + NSMutableDictionary *threadDictionary = [[NSThread currentThread] threadDictionary]; NSString *objectStoreKey = [NSString stringWithFormat:@"RKManagedObjectStore_%p", self]; if (! [threadDictionary valueForKey:objectStoreKey]) { [threadDictionary setObject:[NSMutableDictionary dictionary] forKey:objectStoreKey]; @@ -184,7 +194,8 @@ - (void)removeThreadLocalObjectForKey:(id)key { [[threadDictionary objectForKey:objectStoreKey] removeObjectForKey:key]; } -- (void)clearThreadLocalStorage { +- (void)clearThreadLocalStorage +{ // Clear out our Thread local information NSManagedObjectContext *managedObjectContext = [self threadLocalObjectForKey:RKManagedObjectStoreThreadDictionaryContextKey]; if (managedObjectContext) { @@ -195,7 +206,8 @@ - (void)clearThreadLocalStorage { } } -- (void)dealloc { +- (void)dealloc +{ [[NSNotificationCenter defaultCenter] removeObserver:self]; [self clearThreadLocalStorage]; @@ -220,8 +232,9 @@ - (void)dealloc { Performs the save action for the application, which is to send the save: message to the application's managed object context. */ -- (BOOL)save:(NSError **)error { - NSManagedObjectContext* moc = [self managedObjectContextForCurrentThread]; +- (BOOL)save:(NSError **)error +{ + NSManagedObjectContext *moc = [self managedObjectContextForCurrentThread]; NSError *localError = nil; @try { @@ -230,7 +243,7 @@ - (BOOL)save:(NSError **)error { [self.delegate managedObjectStore:self didFailToSaveContext:moc error:localError exception:nil]; } - NSDictionary* userInfo = [NSDictionary dictionaryWithObject:localError forKey:@"error"]; + NSDictionary *userInfo = [NSDictionary dictionaryWithObject:localError forKey:@"error"]; [[NSNotificationCenter defaultCenter] postNotificationName:RKManagedObjectStoreDidFailSaveNotification object:self userInfo:userInfo]; if ([[localError domain] isEqualToString:@"NSCocoaErrorDomain"]) { @@ -270,7 +283,7 @@ - (BOOL)save:(NSError **)error { return NO; } } - @catch (NSException* e) { + @catch (NSException *e) { if (self.delegate != nil && [self.delegate respondsToSelector:@selector(managedObjectStore:didFailToSaveContext:error:exception:)]) { [self.delegate managedObjectStore:self didFailToSaveContext:moc error:nil exception:e]; } @@ -282,7 +295,8 @@ - (BOOL)save:(NSError **)error { return YES; } -- (NSManagedObjectContext *)newManagedObjectContext { +- (NSManagedObjectContext *)newManagedObjectContext +{ NSManagedObjectContext *managedObjectContext = [[NSManagedObjectContext alloc] init]; [managedObjectContext setPersistentStoreCoordinator:self.persistentStoreCoordinator]; [managedObjectContext setUndoManager:nil]; @@ -292,13 +306,14 @@ - (NSManagedObjectContext *)newManagedObjectContext { return managedObjectContext; } -- (void)createStoreIfNecessaryUsingSeedDatabase:(NSString*)seedDatabase { +- (void)createStoreIfNecessaryUsingSeedDatabase:(NSString *)seedDatabase +{ if (NO == [[NSFileManager defaultManager] fileExistsAtPath:self.pathToStoreFile]) { - NSString* seedDatabasePath = [[NSBundle mainBundle] pathForResource:seedDatabase ofType:nil]; + NSString *seedDatabasePath = [[NSBundle mainBundle] pathForResource:seedDatabase ofType:nil]; NSAssert1(seedDatabasePath, @"Unable to find seed database file '%@' in the Main Bundle, aborting...", seedDatabase); RKLogInfo(@"No existing database found, copying from seed path '%@'", seedDatabasePath); - NSError* error; + NSError *error; if (![[NSFileManager defaultManager] copyItemAtPath:seedDatabasePath toPath:self.pathToStoreFile error:&error]) { if (self.delegate != nil && [self.delegate respondsToSelector:@selector(managedObjectStore:didFailToCopySeedDatabase:error:)]) { [self.delegate managedObjectStore:self didFailToCopySeedDatabase:seedDatabase error:error]; @@ -310,7 +325,8 @@ - (void)createStoreIfNecessaryUsingSeedDatabase:(NSString*)seedDatabase { } } -- (void)createPersistentStoreCoordinator { +- (void)createPersistentStoreCoordinator +{ NSAssert(_managedObjectModel, @"Cannot create persistent store coordinator without a managed object model"); NSAssert(!_persistentStoreCoordinator, @"Cannot create persistent store coordinator: one already exists."); NSURL *storeURL = [NSURL fileURLWithPath:self.pathToStoreFile]; @@ -332,9 +348,10 @@ - (void)createPersistentStoreCoordinator { } } -- (void)deletePersistentStoreUsingSeedDatabaseName:(NSString *)seedFile { - NSURL* storeURL = [NSURL fileURLWithPath:self.pathToStoreFile]; - NSError* error = nil; +- (void)deletePersistentStoreUsingSeedDatabaseName:(NSString *)seedFile +{ + NSURL *storeURL = [NSURL fileURLWithPath:self.pathToStoreFile]; + NSError *error = nil; if ([[NSFileManager defaultManager] fileExistsAtPath:storeURL.path]) { if (![[NSFileManager defaultManager] removeItemAtPath:storeURL.path error:&error]) { if (self.delegate != nil && [self.delegate respondsToSelector:@selector(managedObjectStore:didFailToDeletePersistentStore:error:)]) { @@ -361,17 +378,19 @@ - (void)deletePersistentStoreUsingSeedDatabaseName:(NSString *)seedFile { self.primaryManagedObjectContext = [[self newManagedObjectContext] autorelease]; } -- (void)deletePersistentStore { +- (void)deletePersistentStore +{ [self deletePersistentStoreUsingSeedDatabaseName:nil]; } -- (NSManagedObjectContext *)managedObjectContextForCurrentThread { +- (NSManagedObjectContext *)managedObjectContextForCurrentThread +{ if ([NSThread isMainThread]) { return self.primaryManagedObjectContext; } // Background threads leverage thread-local storage - NSManagedObjectContext* managedObjectContext = [self threadLocalObjectForKey:RKManagedObjectStoreThreadDictionaryContextKey]; + NSManagedObjectContext *managedObjectContext = [self threadLocalObjectForKey:RKManagedObjectStoreThreadDictionaryContextKey]; if (!managedObjectContext) { managedObjectContext = [self newManagedObjectContext]; @@ -389,14 +408,16 @@ - (NSManagedObjectContext *)managedObjectContextForCurrentThread { return managedObjectContext; } -- (void)mergeChangesOnMainThreadWithNotification:(NSNotification*)notification { +- (void)mergeChangesOnMainThreadWithNotification:(NSNotification *)notification +{ assert([NSThread isMainThread]); [self.primaryManagedObjectContext performSelectorOnMainThread:@selector(mergeChangesFromContextDidSaveNotification:) withObject:notification waitUntilDone:YES]; } -- (void)mergeChanges:(NSNotification *)notification { +- (void)mergeChanges:(NSNotification *)notification +{ // Merge changes into the main context on the main thread [self performSelectorOnMainThread:@selector(mergeChangesOnMainThreadWithNotification:) withObject:notification waitUntilDone:YES]; } @@ -404,17 +425,19 @@ - (void)mergeChanges:(NSNotification *)notification { #pragma mark - #pragma mark Helpers -- (NSManagedObject*)objectWithID:(NSManagedObjectID *)objectID { +- (NSManagedObject *)objectWithID:(NSManagedObjectID *)objectID +{ NSAssert(objectID, @"Cannot fetch a managedObject with a nil objectID"); return [[self managedObjectContextForCurrentThread] objectWithID:objectID]; } -- (NSArray*)objectsWithIDs:(NSArray*)objectIDs { - NSMutableArray* objects = [[NSMutableArray alloc] init]; - for (NSManagedObjectID* objectID in objectIDs) { +- (NSArray *)objectsWithIDs:(NSArray *)objectIDs +{ + NSMutableArray *objects = [[NSMutableArray alloc] init]; + for (NSManagedObjectID *objectID in objectIDs) { [objects addObject:[self objectWithID:objectID]]; } - NSArray* objectArray = [NSArray arrayWithArray:objects]; + NSArray *objectArray = [NSArray arrayWithArray:objects]; [objects release]; return objectArray; diff --git a/Code/CoreData/RKManagedObjectThreadSafeInvocation.h b/Code/CoreData/RKManagedObjectThreadSafeInvocation.h index 8d259715ab..2b6fb67467 100644 --- a/Code/CoreData/RKManagedObjectThreadSafeInvocation.h +++ b/Code/CoreData/RKManagedObjectThreadSafeInvocation.h @@ -21,18 +21,17 @@ #import "RKManagedObjectStore.h" @interface RKManagedObjectThreadSafeInvocation : NSInvocation { - NSMutableDictionary* _argumentKeyPaths; - RKManagedObjectStore* _objectStore; + NSMutableDictionary *_argumentKeyPaths; } -@property (nonatomic, retain) RKManagedObjectStore* objectStore; +@property (nonatomic, retain) RKManagedObjectStore *objectStore; -+ (RKManagedObjectThreadSafeInvocation*)invocationWithMethodSignature:(NSMethodSignature*)methodSignature; -- (void)setManagedObjectKeyPaths:(NSSet*)keyPaths forArgument:(NSInteger)index; ++ (RKManagedObjectThreadSafeInvocation *)invocationWithMethodSignature:(NSMethodSignature *)methodSignature; +- (void)setManagedObjectKeyPaths:(NSSet *)keyPaths forArgument:(NSInteger)index; - (void)invokeOnMainThread; // Private -- (void)serializeManagedObjectsForArgument:(id)argument withKeyPaths:(NSSet*)keyPaths; -- (void)deserializeManagedObjectIDsForArgument:(id)argument withKeyPaths:(NSSet*)keyPaths; +- (void)serializeManagedObjectsForArgument:(id)argument withKeyPaths:(NSSet *)keyPaths; +- (void)deserializeManagedObjectIDsForArgument:(id)argument withKeyPaths:(NSSet *)keyPaths; @end diff --git a/Code/CoreData/RKManagedObjectThreadSafeInvocation.m b/Code/CoreData/RKManagedObjectThreadSafeInvocation.m index d4d805c5e1..d4012166cc 100644 --- a/Code/CoreData/RKManagedObjectThreadSafeInvocation.m +++ b/Code/CoreData/RKManagedObjectThreadSafeInvocation.m @@ -24,20 +24,23 @@ @implementation RKManagedObjectThreadSafeInvocation @synthesize objectStore = _objectStore; -+ (RKManagedObjectThreadSafeInvocation*)invocationWithMethodSignature:(NSMethodSignature*)methodSignature { - return (RKManagedObjectThreadSafeInvocation*) [super invocationWithMethodSignature:methodSignature]; ++ (RKManagedObjectThreadSafeInvocation *)invocationWithMethodSignature:(NSMethodSignature *)methodSignature +{ + return (RKManagedObjectThreadSafeInvocation *)[super invocationWithMethodSignature:methodSignature]; } -- (void)setManagedObjectKeyPaths:(NSSet*)keyPaths forArgument:(NSInteger)index { +- (void)setManagedObjectKeyPaths:(NSSet *)keyPaths forArgument:(NSInteger)index +{ if (nil == _argumentKeyPaths) { _argumentKeyPaths = [[NSMutableDictionary alloc] init]; } - NSNumber* argumentIndex = [NSNumber numberWithInteger:index]; + NSNumber *argumentIndex = [NSNumber numberWithInteger:index]; [_argumentKeyPaths setObject:keyPaths forKey:argumentIndex]; } -- (void)setValue:(id)value forKeyPathOrKey:(NSString *)keyPath object:(id)object { +- (void)setValue:(id)value forKeyPathOrKey:(NSString *)keyPath object:(id)object +{ [object setValue:value forKeyPath:keyPath]; id testValue = [object valueForKeyPath:keyPath]; @@ -49,17 +52,18 @@ - (void)setValue:(id)value forKeyPathOrKey:(NSString *)keyPath object:(id)object } } -- (void)serializeManagedObjectsForArgument:(id)argument withKeyPaths:(NSSet*)keyPaths { - for (NSString* keyPath in keyPaths) { +- (void)serializeManagedObjectsForArgument:(id)argument withKeyPaths:(NSSet *)keyPaths +{ + for (NSString *keyPath in keyPaths) { id value = [argument valueForKeyPath:keyPath]; if ([value isKindOfClass:[NSManagedObject class]]) { - NSManagedObjectID *objectID = [(NSManagedObject*)value objectID]; + NSManagedObjectID *objectID = [(NSManagedObject *)value objectID]; [self setValue:objectID forKeyPathOrKey:keyPath object:argument]; } else if ([value respondsToSelector:@selector(allObjects)]) { id collection = [[[[[value class] alloc] init] autorelease] mutableCopy]; for (id subObject in value) { if ([subObject isKindOfClass:[NSManagedObject class]]) { - [collection addObject:[(NSManagedObject*)subObject objectID]]; + [collection addObject:[(NSManagedObject *)subObject objectID]]; } else { [collection addObject:subObject]; } @@ -71,12 +75,13 @@ - (void)serializeManagedObjectsForArgument:(id)argument withKeyPaths:(NSSet*)key } } -- (void)deserializeManagedObjectIDsForArgument:(id)argument withKeyPaths:(NSSet*)keyPaths { - for (NSString* keyPath in keyPaths) { +- (void)deserializeManagedObjectIDsForArgument:(id)argument withKeyPaths:(NSSet *)keyPaths +{ + for (NSString *keyPath in keyPaths) { id value = [argument valueForKeyPath:keyPath]; if ([value isKindOfClass:[NSManagedObjectID class]]) { NSAssert(self.objectStore, @"Object store cannot be nil"); - NSManagedObject* managedObject = [self.objectStore objectWithID:(NSManagedObjectID*)value]; + NSManagedObject *managedObject = [self.objectStore objectWithID:(NSManagedObjectID *)value]; NSAssert(managedObject, @"Expected managed object for ID %@, got nil", value); [self setValue:managedObject forKeyPathOrKey:keyPath object:argument]; } else if ([value respondsToSelector:@selector(allObjects)]) { @@ -84,7 +89,7 @@ - (void)deserializeManagedObjectIDsForArgument:(id)argument withKeyPaths:(NSSet* for (id subObject in value) { if ([subObject isKindOfClass:[NSManagedObjectID class]]) { NSAssert(self.objectStore, @"Object store cannot be nil"); - NSManagedObject* managedObject = [self.objectStore objectWithID:(NSManagedObjectID*)subObject]; + NSManagedObject *managedObject = [self.objectStore objectWithID:(NSManagedObjectID *)subObject]; [collection addObject:managedObject]; } else { [collection addObject:subObject]; @@ -96,9 +101,10 @@ - (void)deserializeManagedObjectIDsForArgument:(id)argument withKeyPaths:(NSSet* } } } -- (void)serializeManagedObjects { - for (NSNumber* argumentIndex in _argumentKeyPaths) { - NSSet* managedKeyPaths = [_argumentKeyPaths objectForKey:argumentIndex]; +- (void)serializeManagedObjects +{ + for (NSNumber *argumentIndex in _argumentKeyPaths) { + NSSet *managedKeyPaths = [_argumentKeyPaths objectForKey:argumentIndex]; id argument = nil; [self getArgument:&argument atIndex:[argumentIndex intValue]]; if (argument) { @@ -107,9 +113,10 @@ - (void)serializeManagedObjects { } } -- (void)deserializeManagedObjects { - for (NSNumber* argumentIndex in _argumentKeyPaths) { - NSSet* managedKeyPaths = [_argumentKeyPaths objectForKey:argumentIndex]; +- (void)deserializeManagedObjects +{ + for (NSNumber *argumentIndex in _argumentKeyPaths) { + NSSet *managedKeyPaths = [_argumentKeyPaths objectForKey:argumentIndex]; id argument = nil; [self getArgument:&argument atIndex:[argumentIndex intValue]]; if (argument) { @@ -118,19 +125,22 @@ - (void)deserializeManagedObjects { } } -- (void)performInvocationOnMainThread { +- (void)performInvocationOnMainThread +{ [self deserializeManagedObjects]; [self invoke]; } -- (void)invokeOnMainThread { +- (void)invokeOnMainThread +{ [self retain]; [self serializeManagedObjects]; [self performSelectorOnMainThread:@selector(performInvocationOnMainThread) withObject:nil waitUntilDone:YES]; [self release]; } -- (void)dealloc { +- (void)dealloc +{ [_argumentKeyPaths release]; [_objectStore release]; [super dealloc]; diff --git a/Code/CoreData/RKObjectMappingProvider+CoreData.m b/Code/CoreData/RKObjectMappingProvider+CoreData.m index efdd421de2..33bda1c516 100644 --- a/Code/CoreData/RKObjectMappingProvider+CoreData.m +++ b/Code/CoreData/RKObjectMappingProvider+CoreData.m @@ -13,12 +13,14 @@ RK_FIX_CATEGORY_BUG(RKObjectMappingProvider_CoreData) @implementation RKObjectMappingProvider (CoreData) -- (void)setObjectMapping:(RKObjectMappingDefinition *)objectMapping forResourcePathPattern:(NSString *)resourcePath withFetchRequestBlock:(RKObjectMappingProviderFetchRequestBlock)fetchRequestBlock { +- (void)setObjectMapping:(RKObjectMappingDefinition *)objectMapping forResourcePathPattern:(NSString *)resourcePath withFetchRequestBlock:(RKObjectMappingProviderFetchRequestBlock)fetchRequestBlock +{ [self setEntry:[RKObjectMappingProviderContextEntry contextEntryWithMapping:objectMapping userData:Block_copy(fetchRequestBlock)] forResourcePathPattern:resourcePath]; } -- (NSFetchRequest *)fetchRequestForResourcePath:(NSString *)resourcePath { +- (NSFetchRequest *)fetchRequestForResourcePath:(NSString *)resourcePath +{ RKObjectMappingProviderContextEntry *entry = [self entryForResourcePath:resourcePath]; if (entry.userData) { NSFetchRequest *(^fetchRequestBlock)(NSString *) = entry.userData; diff --git a/Code/CoreData/RKObjectPropertyInspector+CoreData.h b/Code/CoreData/RKObjectPropertyInspector+CoreData.h index c04d05dc55..b9056bcf06 100644 --- a/Code/CoreData/RKObjectPropertyInspector+CoreData.h +++ b/Code/CoreData/RKObjectPropertyInspector+CoreData.h @@ -22,11 +22,11 @@ @interface RKObjectPropertyInspector (CoreData) -- (NSDictionary *)propertyNamesAndTypesForEntity:(NSEntityDescription*)entity; +- (NSDictionary *)propertyNamesAndTypesForEntity:(NSEntityDescription *)entity; /** Returns the Class type of the specified property on the object class */ -- (Class)typeForProperty:(NSString*)propertyName ofEntity:(NSEntityDescription*)entity; +- (Class)typeForProperty:(NSString *)propertyName ofEntity:(NSEntityDescription *)entity; @end diff --git a/Code/CoreData/RKObjectPropertyInspector+CoreData.m b/Code/CoreData/RKObjectPropertyInspector+CoreData.m index 9767b6924a..267b6e448b 100644 --- a/Code/CoreData/RKObjectPropertyInspector+CoreData.m +++ b/Code/CoreData/RKObjectPropertyInspector+CoreData.m @@ -33,30 +33,31 @@ @implementation RKObjectPropertyInspector (CoreData) -- (NSDictionary *)propertyNamesAndTypesForEntity:(NSEntityDescription*)entity { - NSMutableDictionary* propertyNamesAndTypes = [_cachedPropertyNamesAndTypes objectForKey:[entity name]]; +- (NSDictionary *)propertyNamesAndTypesForEntity:(NSEntityDescription *)entity +{ + NSMutableDictionary *propertyNamesAndTypes = [_cachedPropertyNamesAndTypes objectForKey:[entity name]]; if (propertyNamesAndTypes) { return propertyNamesAndTypes; } propertyNamesAndTypes = [NSMutableDictionary dictionary]; - for (NSString* name in [entity attributesByName]) { - NSAttributeDescription* attributeDescription = [[entity attributesByName] valueForKey:name]; + for (NSString *name in [entity attributesByName]) { + NSAttributeDescription *attributeDescription = [[entity attributesByName] valueForKey:name]; if ([attributeDescription attributeValueClassName]) { [propertyNamesAndTypes setValue:NSClassFromString([attributeDescription attributeValueClassName]) forKey:name]; } else if ([attributeDescription attributeType] == NSTransformableAttributeType && ![name isEqualToString:@"_mapkit_hasPanoramaID"]) { - const char* className = [[entity managedObjectClassName] cStringUsingEncoding:NSUTF8StringEncoding]; - const char* propertyName = [name cStringUsingEncoding:NSUTF8StringEncoding]; + const char *className = [[entity managedObjectClassName] cStringUsingEncoding:NSUTF8StringEncoding]; + const char *propertyName = [name cStringUsingEncoding:NSUTF8StringEncoding]; Class managedObjectClass = objc_getClass(className); // property_getAttributes() returns everything we need to implement this... // See: http://developer.apple.com/mac/library/DOCUMENTATION/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtPropertyIntrospection.html#//apple_ref/doc/uid/TP40008048-CH101-SW5 objc_property_t prop = class_getProperty(managedObjectClass, propertyName); - NSString* attributeString = [NSString stringWithCString:property_getAttributes(prop) encoding:NSUTF8StringEncoding]; - const char* destinationClassName = [[RKObjectPropertyInspector propertyTypeFromAttributeString:attributeString] cStringUsingEncoding:NSUTF8StringEncoding]; + NSString *attributeString = [NSString stringWithCString:property_getAttributes(prop) encoding:NSUTF8StringEncoding]; + const char *destinationClassName = [[RKObjectPropertyInspector propertyTypeFromAttributeString:attributeString] cStringUsingEncoding:NSUTF8StringEncoding]; Class destinationClass = objc_getClass(destinationClassName); if (destinationClass) { [propertyNamesAndTypes setObject:destinationClass forKey:name]; @@ -64,12 +65,12 @@ - (NSDictionary *)propertyNamesAndTypesForEntity:(NSEntityDescription*)entity { } } - for (NSString* name in [entity relationshipsByName]) { - NSRelationshipDescription* relationshipDescription = [[entity relationshipsByName] valueForKey:name]; + for (NSString *name in [entity relationshipsByName]) { + NSRelationshipDescription *relationshipDescription = [[entity relationshipsByName] valueForKey:name]; if ([relationshipDescription isToMany]) { [propertyNamesAndTypes setValue:[NSSet class] forKey:name]; } else { - NSEntityDescription* destinationEntity = [relationshipDescription destinationEntity]; + NSEntityDescription *destinationEntity = [relationshipDescription destinationEntity]; Class destinationClass = NSClassFromString([destinationEntity managedObjectClassName]); [propertyNamesAndTypes setValue:destinationClass forKey:name]; } @@ -80,7 +81,8 @@ - (NSDictionary *)propertyNamesAndTypesForEntity:(NSEntityDescription*)entity { return propertyNamesAndTypes; } -- (Class)typeForProperty:(NSString*)propertyName ofEntity:(NSEntityDescription*)entity { +- (Class)typeForProperty:(NSString *)propertyName ofEntity:(NSEntityDescription *)entity +{ return [[self propertyNamesAndTypesForEntity:entity] valueForKey:propertyName]; } diff --git a/Code/CoreData/RKSearchWord.h b/Code/CoreData/RKSearchWord.h index e030fff75d..0a4e71b228 100644 --- a/Code/CoreData/RKSearchWord.h +++ b/Code/CoreData/RKSearchWord.h @@ -25,16 +25,16 @@ extern NSString * const RKSearchWordPrimaryKeyAttribute; @interface RKSearchWord : NSManagedObject -@property (nonatomic, retain) NSString* word; -@property (nonatomic, retain) NSSet* searchableManagedObjects; +@property (nonatomic, retain) NSString *word; +@property (nonatomic, retain) NSSet *searchableManagedObjects; @end @interface RKSearchWord (SearchableManagedObjectsAccessors) -- (void)addSearchableManagedObjectsObject:(RKSearchableManagedObject*)searchableManagedObject; -- (void)removeSearchableManagedObjectsObject:(RKSearchableManagedObject*)searchableManagedObject; -- (void)addSearchableManagedObjects:(NSSet*)searchableManagedObjects; -- (void)removeSearchableManagedObjects:(NSSet*)searchableManagedObjects; +- (void)addSearchableManagedObjectsObject:(RKSearchableManagedObject *)searchableManagedObject; +- (void)removeSearchableManagedObjectsObject:(RKSearchableManagedObject *)searchableManagedObject; +- (void)addSearchableManagedObjects:(NSSet *)searchableManagedObjects; +- (void)removeSearchableManagedObjects:(NSSet *)searchableManagedObjects; @end diff --git a/Code/CoreData/RKSearchWordObserver.m b/Code/CoreData/RKSearchWordObserver.m index 03e040c6bb..8f6f781953 100644 --- a/Code/CoreData/RKSearchWordObserver.m +++ b/Code/CoreData/RKSearchWordObserver.m @@ -19,7 +19,8 @@ @implementation RKSearchWordObserver -+ (RKSearchWordObserver *)sharedObserver { ++ (RKSearchWordObserver *)sharedObserver +{ if (! sharedSearchWordObserver) { sharedSearchWordObserver = [[RKSearchWordObserver alloc] init]; } @@ -27,7 +28,8 @@ + (RKSearchWordObserver *)sharedObserver { return sharedSearchWordObserver; } -- (id)init { +- (id)init +{ self = [super init]; if (self) { [[NSNotificationCenter defaultCenter] addObserver:self @@ -39,12 +41,14 @@ - (id)init { return self; } -- (void)dealloc { +- (void)dealloc +{ [[NSNotificationCenter defaultCenter] removeObserver:self]; [super dealloc]; } -- (void)managedObjectContextWillSaveNotification:(NSNotification *)notification { +- (void)managedObjectContextWillSaveNotification:(NSNotification *)notification +{ NSManagedObjectContext *context = [notification object]; NSSet *candidateObjects = [[NSSet setWithSet:context.insertedObjects] setByAddingObjectsFromSet:context.updatedObjects]; diff --git a/Code/CoreData/RKSearchableManagedObject.m b/Code/CoreData/RKSearchableManagedObject.m index df667e91c3..640641df1b 100644 --- a/Code/CoreData/RKSearchableManagedObject.m +++ b/Code/CoreData/RKSearchableManagedObject.m @@ -48,7 +48,7 @@ + (NSPredicate *)predicateForSearchWithText:(NSString *)searchText searchMode:(R - (void)refreshSearchWords { - NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; RKLogDebug(@"Refreshing search words for %@ %@", NSStringFromClass([self class]), [self objectID]); NSMutableSet *searchWords = [NSMutableSet set]; diff --git a/Code/Network/NSData+RKAdditions.m b/Code/Network/NSData+RKAdditions.m index 5ae5fa3ee2..7011d38b0f 100644 --- a/Code/Network/NSData+RKAdditions.m +++ b/Code/Network/NSData+RKAdditions.m @@ -26,17 +26,18 @@ @implementation NSData (RKAdditions) -- (NSString *)MD5 { +- (NSString *)MD5 +{ // Create byte array of unsigned chars unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH]; // Create 16 byte MD5 hash value, store in buffer - CC_MD5(self.bytes, (CC_LONG) self.length, md5Buffer); + CC_MD5(self.bytes, (CC_LONG)self.length, md5Buffer); // Convert unsigned char buffer to NSString of hex values - NSMutableString* output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2]; + NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH *2]; for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) { - [output appendFormat:@"%02x",md5Buffer[i]]; + [output appendFormat:@"%02x", md5Buffer[i]]; } return output; diff --git a/Code/Network/NSObject+URLEncoding.h b/Code/Network/NSObject+URLEncoding.h index 5564221db5..aaa7c9a897 100644 --- a/Code/Network/NSObject+URLEncoding.h +++ b/Code/Network/NSObject+URLEncoding.h @@ -14,6 +14,6 @@ * * @returns A UTF-8 encoded string representation of the object */ -- (NSString*)URLEncodedString; +- (NSString *)URLEncodedString; @end diff --git a/Code/Network/NSObject+URLEncoding.m b/Code/Network/NSObject+URLEncoding.m index 54c8a927c3..002ea51d63 100644 --- a/Code/Network/NSObject+URLEncoding.m +++ b/Code/Network/NSObject+URLEncoding.m @@ -11,9 +11,10 @@ @implementation NSObject (URLEncoding) -- (NSString*)URLEncodedString { +- (NSString *)URLEncodedString +{ NSString *string = [NSString stringWithFormat:@"%@", self]; - NSString *encodedString = (NSString*)CFURLCreateStringByAddingPercentEscapes(NULL, + NSString *encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)string, NULL, (CFStringRef)@"!*'();:@&=+$,/?%#[]", diff --git a/Code/Network/RKClient.h b/Code/Network/RKClient.h index 596481099f..9b3a7b5fd0 100644 --- a/Code/Network/RKClient.h +++ b/Code/Network/RKClient.h @@ -95,28 +95,7 @@ @see RKRequestSerializable */ @interface RKClient : NSObject { - RKURL *_baseURL; - RKRequestAuthenticationType _authenticationType; - NSString *_username; - NSString *_password; - NSString *_OAuth1ConsumerKey; - NSString *_OAuth1ConsumerSecret; - NSString *_OAuth1AccessToken; - NSString *_OAuth1AccessTokenSecret; - NSString *_OAuth2AccessToken; - NSString *_OAuth2RefreshToken; - NSMutableDictionary *_HTTPHeaders; - RKReachabilityObserver *_reachabilityObserver; - NSString *_serviceUnavailableAlertTitle; - NSString *_serviceUnavailableAlertMessage; - BOOL _serviceUnavailableAlertEnabled; - RKRequestQueue *_requestQueue; - RKRequestCache *_requestCache; - RKRequestCachePolicy _cachePolicy; NSMutableSet *_additionalRootCertificates; - BOOL _disableCertificateValidation; - NSStringEncoding _defaultHTTPEncoding; - NSString *_runLoopMode; // Queue suspension flags BOOL _awaitingReachabilityDetermination; diff --git a/Code/Network/RKClient.m b/Code/Network/RKClient.m index 70eb174e65..d6b3d2b5ea 100644 --- a/Code/Network/RKClient.m +++ b/Code/Network/RKClient.m @@ -47,7 +47,7 @@ return [[[RKClient sharedClient].baseURL URLByAppendingResourcePath:resourcePath] absoluteString]; } -NSString *RKMakePathWithObjectAddingEscapes(NSString* pattern, id object, BOOL addEscapes) { +NSString *RKMakePathWithObjectAddingEscapes(NSString *pattern, id object, BOOL addEscapes) { NSCAssert(pattern != NULL, @"Pattern string must not be empty in order to create a path from an interpolated object."); NSCAssert(object != NULL, @"Object provided is invalid; cannot create a path from a NULL object"); RKPathMatcher *matcher = [RKPathMatcher matcherWithPattern:pattern]; @@ -97,25 +97,30 @@ @implementation RKClient @synthesize cacheTimeoutInterval = _cacheTimeoutInterval; @synthesize runLoopMode = _runLoopMode; -+ (RKClient *)sharedClient { ++ (RKClient *)sharedClient +{ return sharedClient; } -+ (void)setSharedClient:(RKClient *)client { ++ (void)setSharedClient:(RKClient *)client +{ [sharedClient release]; sharedClient = [client retain]; } -+ (RKClient *)clientWithBaseURLString:(NSString *)baseURLString { ++ (RKClient *)clientWithBaseURLString:(NSString *)baseURLString +{ return [self clientWithBaseURL:[RKURL URLWithString:baseURLString]]; } -+ (RKClient *)clientWithBaseURL:(NSURL *)baseURL { ++ (RKClient *)clientWithBaseURL:(NSURL *)baseURL +{ RKClient *client = [[[self alloc] initWithBaseURL:baseURL] autorelease]; return client; } -+ (RKClient *)clientWithBaseURL:(NSString *)baseURL username:(NSString *)username password:(NSString *)password { ++ (RKClient *)clientWithBaseURL:(NSString *)baseURL username:(NSString *)username password:(NSString *)password +{ RKClient *client = [RKClient clientWithBaseURLString:baseURL]; client.authenticationType = RKRequestAuthenticationTypeHTTPBasic; client.username = username; @@ -123,7 +128,8 @@ + (RKClient *)clientWithBaseURL:(NSString *)baseURL username:(NSString *)usernam return client; } -- (id)init { +- (id)init +{ self = [super init]; if (self) { self.HTTPHeaders = [NSMutableDictionary dictionary]; @@ -149,7 +155,8 @@ - (id)init { return self; } -- (id)initWithBaseURL:(NSURL *)baseURL { +- (id)initWithBaseURL:(NSURL *)baseURL +{ self = [self init]; if (self) { self.cachePolicy = RKRequestCachePolicyDefault; @@ -166,11 +173,13 @@ - (id)initWithBaseURL:(NSURL *)baseURL { return self; } -- (id)initWithBaseURLString:(NSString *)baseURLString { +- (id)initWithBaseURLString:(NSString *)baseURLString +{ return [self initWithBaseURL:[RKURL URLWithString:baseURLString]]; } -- (void)dealloc { +- (void)dealloc +{ [[NSNotificationCenter defaultCenter] removeObserver:self]; // Allow KVO to fire @@ -196,14 +205,16 @@ - (void)dealloc { [super dealloc]; } -- (NSString *)cachePath { +- (NSString *)cachePath +{ NSString *cacheDirForClient = [NSString stringWithFormat:@"RKClientRequestCache-%@", [self.baseURL host]]; NSString *cachePath = [[RKDirectory cachesDirectory] stringByAppendingPathComponent:cacheDirForClient]; return cachePath; } -- (BOOL)isNetworkReachable { +- (BOOL)isNetworkReachable +{ BOOL isNetworkReachable = YES; if (self.reachabilityObserver) { isNetworkReachable = [self.reachabilityObserver isNetworkReachable]; @@ -212,7 +223,8 @@ - (BOOL)isNetworkReachable { return isNetworkReachable; } -- (void)configureRequest:(RKRequest *)request { +- (void)configureRequest:(RKRequest *)request +{ request.additionalHTTPHeaders = _HTTPHeaders; request.authenticationType = self.authenticationType; request.username = self.username; @@ -248,15 +260,18 @@ - (void)configureRequest:(RKRequest *)request { request.OAuth2RefreshToken = self.OAuth2RefreshToken; } -- (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)header { +- (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)header +{ [_HTTPHeaders setValue:value forKey:header]; } -- (void)addRootCertificate:(SecCertificateRef)cert { +- (void)addRootCertificate:(SecCertificateRef)cert +{ [_additionalRootCertificates addObject:(id)cert]; } -- (void)reachabilityObserverDidChange:(NSDictionary *)change { +- (void)reachabilityObserverDidChange:(NSDictionary *)change +{ RKReachabilityObserver *oldReachabilityObserver = [change objectForKey:NSKeyValueChangeOldKey]; RKReachabilityObserver *newReachabilityObserver = [change objectForKey:NSKeyValueChangeNewKey]; @@ -290,7 +305,8 @@ - (void)reachabilityObserverDidChange:(NSDictionary *)change { } } -- (void)baseURLDidChange:(NSDictionary *)change { +- (void)baseURLDidChange:(NSDictionary *)change +{ RKURL *newBaseURL = [change objectForKey:NSKeyValueChangeNewKey]; // Don't crash if baseURL is nil'd out (i.e. dealloc) @@ -312,7 +328,8 @@ - (void)baseURLDidChange:(NSDictionary *)change { } } -- (void)requestQueueDidChange:(NSDictionary *)change { +- (void)requestQueueDidChange:(NSDictionary *)change +{ if (! _awaitingReachabilityDetermination) { return; } @@ -327,7 +344,8 @@ - (void)requestQueueDidChange:(NSDictionary *)change { } } -- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { +- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context +{ if ([keyPath isEqualToString:@"baseURL"]) { [self baseURLDidChange:change]; } else if ([keyPath isEqualToString:@"requestQueue"]) { @@ -337,7 +355,8 @@ - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(N } } -- (RKRequest *)requestWithResourcePath:(NSString *)resourcePath { +- (RKRequest *)requestWithResourcePath:(NSString *)resourcePath +{ RKRequest *request = [[RKRequest alloc] initWithURL:[self.baseURL URLByAppendingResourcePath:resourcePath]]; [self configureRequest:request]; [request autorelease]; @@ -345,7 +364,8 @@ - (RKRequest *)requestWithResourcePath:(NSString *)resourcePath { return request; } -- (RKRequest *)requestWithResourcePath:(NSString *)resourcePath delegate:(NSObject *)delegate { +- (RKRequest *)requestWithResourcePath:(NSString *)resourcePath delegate:(NSObject *)delegate +{ RKRequest *request = [self requestWithResourcePath:resourcePath]; request.delegate = delegate; @@ -356,8 +376,9 @@ - (RKRequest *)requestWithResourcePath:(NSString *)resourcePath delegate:(NSObje // Asynchronous Requests /////////////////////////////////////////////////////////////////////////////////////////////////////////// -- (RKRequest *)load:(NSString *)resourcePath method:(RKRequestMethod)method params:(NSObject *)params delegate:(id)delegate { - RKURL* resourcePathURL = nil; +- (RKRequest *)load:(NSString *)resourcePath method:(RKRequestMethod)method params:(NSObject *)params delegate:(id)delegate +{ + RKURL *resourcePathURL = nil; if (method == RKRequestMethodGET) { resourcePathURL = [self.baseURL URLByAppendingResourcePath:resourcePath queryParameters:(NSDictionary *)params]; } else { @@ -376,34 +397,41 @@ - (RKRequest *)load:(NSString *)resourcePath method:(RKRequestMethod)method para return request; } -- (RKRequest *)get:(NSString *)resourcePath delegate:(id)delegate { +- (RKRequest *)get:(NSString *)resourcePath delegate:(id)delegate +{ return [self load:resourcePath method:RKRequestMethodGET params:nil delegate:delegate]; } -- (RKRequest *)get:(NSString *)resourcePath queryParameters:(NSDictionary *)queryParameters delegate:(id)delegate { +- (RKRequest *)get:(NSString *)resourcePath queryParameters:(NSDictionary *)queryParameters delegate:(id)delegate +{ return [self load:resourcePath method:RKRequestMethodGET params:queryParameters delegate:delegate]; } -- (RKRequest *)post:(NSString *)resourcePath params:(NSObject *)params delegate:(id)delegate { +- (RKRequest *)post:(NSString *)resourcePath params:(NSObject *)params delegate:(id)delegate +{ return [self load:resourcePath method:RKRequestMethodPOST params:params delegate:delegate]; } -- (RKRequest *)put:(NSString *)resourcePath params:(NSObject *)params delegate:(id)delegate { +- (RKRequest *)put:(NSString *)resourcePath params:(NSObject *)params delegate:(id)delegate +{ return [self load:resourcePath method:RKRequestMethodPUT params:params delegate:delegate]; } -- (RKRequest *)delete:(NSString *)resourcePath delegate:(id)delegate { +- (RKRequest *)delete:(NSString *)resourcePath delegate:(id)delegate +{ return [self load:resourcePath method:RKRequestMethodDELETE params:nil delegate:delegate]; } -- (void)serviceDidBecomeUnavailableNotification:(NSNotification *)notification { +- (void)serviceDidBecomeUnavailableNotification:(NSNotification *)notification +{ if (self.serviceUnavailableAlertEnabled) { RKAlertWithTitle(self.serviceUnavailableAlertMessage, self.serviceUnavailableAlertTitle); } } -- (void)reachabilityWasDetermined:(NSNotification *)notification { - RKReachabilityObserver *observer = (RKReachabilityObserver *) [notification object]; +- (void)reachabilityWasDetermined:(NSNotification *)notification +{ + RKReachabilityObserver *observer = (RKReachabilityObserver *)[notification object]; NSAssert(observer == self.reachabilityObserver, @"Received unexpected reachability notification from inappropriate reachability observer"); RKLogDebug(@"Reachability to host '%@' determined for client %@, unsuspending queue %@", observer.host, self, self.requestQueue); @@ -415,46 +443,53 @@ - (void)reachabilityWasDetermined:(NSNotification *)notification { #pragma mark - Deprecations // deprecated -- (RKRequestCache *)cache { +- (RKRequestCache *)cache +{ return _requestCache; } // deprecated -- (void)setCache:(RKRequestCache *)requestCache { +- (void)setCache:(RKRequestCache *)requestCache +{ self.requestCache = requestCache; } #pragma mark - Block Request Dispatching -- (RKRequest *)sendRequestToResourcePath:(NSString *)resourcePath usingBlock:(void (^)(RKRequest *request))block { +- (RKRequest *)sendRequestToResourcePath:(NSString *)resourcePath usingBlock:(void (^)(RKRequest *request))block +{ RKRequest *request = [self requestWithResourcePath:resourcePath]; if (block) block(request); [request send]; return request; } -- (void)get:(NSString *)resourcePath usingBlock:(void (^)(RKRequest *request))block { +- (void)get:(NSString *)resourcePath usingBlock:(void (^)(RKRequest *request))block +{ [self sendRequestToResourcePath:resourcePath usingBlock:^(RKRequest *request) { request.method = RKRequestMethodGET; block(request); }]; } -- (void)post:(NSString *)resourcePath usingBlock:(void (^)(RKRequest *request))block { +- (void)post:(NSString *)resourcePath usingBlock:(void (^)(RKRequest *request))block +{ [self sendRequestToResourcePath:resourcePath usingBlock:^(RKRequest *request) { request.method = RKRequestMethodPOST; block(request); }]; } -- (void)put:(NSString *)resourcePath usingBlock:(void (^)(RKRequest *request))block { +- (void)put:(NSString *)resourcePath usingBlock:(void (^)(RKRequest *request))block +{ [self sendRequestToResourcePath:resourcePath usingBlock:^(RKRequest *request) { request.method = RKRequestMethodPUT; block(request); }]; } -- (void)delete:(NSString *)resourcePath usingBlock:(void (^)(RKRequest *request))block { +- (void)delete:(NSString *)resourcePath usingBlock:(void (^)(RKRequest *request))block +{ [self sendRequestToResourcePath:resourcePath usingBlock:^(RKRequest *request) { request.method = RKRequestMethodDELETE; block(request); @@ -462,23 +497,28 @@ - (void)delete:(NSString *)resourcePath usingBlock:(void (^)(RKRequest *request) } // deprecated -- (BOOL)isNetworkAvailable { +- (BOOL)isNetworkAvailable +{ return [self isNetworkReachable]; } -- (NSString *)resourcePath:(NSString *)resourcePath withQueryParams:(NSDictionary *)queryParams { +- (NSString *)resourcePath:(NSString *)resourcePath withQueryParams:(NSDictionary *)queryParams +{ return RKPathAppendQueryParams(resourcePath, queryParams); } -- (NSURL *)URLForResourcePath:(NSString *)resourcePath { +- (NSURL *)URLForResourcePath:(NSString *)resourcePath +{ return [self.baseURL URLByAppendingResourcePath:resourcePath]; } -- (NSString *)URLPathForResourcePath:(NSString *)resourcePath { +- (NSString *)URLPathForResourcePath:(NSString *)resourcePath +{ return [[self URLForResourcePath:resourcePath] absoluteString]; } -- (NSURL *)URLForResourcePath:(NSString *)resourcePath queryParams:(NSDictionary *)queryParams { +- (NSURL *)URLForResourcePath:(NSString *)resourcePath queryParams:(NSDictionary *)queryParams +{ return [self.baseURL URLByAppendingResourcePath:resourcePath queryParameters:queryParams]; } diff --git a/Code/Network/RKOAuthClient.h b/Code/Network/RKOAuthClient.h index 1b051d945c..b0ccde90c5 100644 --- a/Code/Network/RKOAuthClient.h +++ b/Code/Network/RKOAuthClient.h @@ -97,16 +97,7 @@ typedef enum RKOAuthClientErrors { @see RKOAuthClientDelegate */ -@interface RKOAuthClient : NSObject { - NSString *_clientID; - NSString *_clientSecret; - NSString *_authorizationCode; - NSString *_authorizationURL; - NSString *_callbackURL; - NSString *_accessToken; - id _delegate; -} - +@interface RKOAuthClient : NSObject ///----------------------------------------------------------------------------- /// @name Creating an RKOAuthClient diff --git a/Code/Network/RKOAuthClient.m b/Code/Network/RKOAuthClient.m index 7642f4d912..d70f64a5ad 100644 --- a/Code/Network/RKOAuthClient.m +++ b/Code/Network/RKOAuthClient.m @@ -34,12 +34,14 @@ @implementation RKOAuthClient @synthesize delegate = _delegate; @synthesize accessToken = _accessToken; -+ (RKOAuthClient *)clientWithClientID:(NSString *)clientID secret:(NSString *)secret { ++ (RKOAuthClient *)clientWithClientID:(NSString *)clientID secret:(NSString *)secret +{ RKOAuthClient *client = [[[self alloc] initWithClientID:clientID secret:secret] autorelease]; return client; } -- (id)initWithClientID:(NSString *)clientID secret:(NSString *)secret { +- (id)initWithClientID:(NSString *)clientID secret:(NSString *)secret +{ self = [super init]; if (self) { _clientID = [clientID copy]; @@ -49,7 +51,8 @@ - (id)initWithClientID:(NSString *)clientID secret:(NSString *)secret { return self; } -- (void)dealloc { +- (void)dealloc +{ [_clientID release]; [_clientSecret release]; [_accessToken release]; @@ -57,7 +60,8 @@ - (void)dealloc { [super dealloc]; } -- (void)validateAuthorizationCode { +- (void)validateAuthorizationCode +{ NSString *httpBody = [NSString stringWithFormat:@"client_id=%@&client_secret=%@&code=%@&redirect_uri=%@&grant_type=authorization_code", _clientID, _clientSecret, _authorizationCode, _callbackURL]; NSURL *URL = [NSURL URLWithString:_authorizationURL]; @@ -68,13 +72,14 @@ - (void)validateAuthorizationCode { [theRequest send]; } -- (void)request:(RKRequest *)request didLoadResponse:(RKResponse *)response { +- (void)request:(RKRequest *)request didLoadResponse:(RKResponse *)response +{ NSError *error = nil; NSString *errorResponse = nil; //Use the parsedBody answer in NSDictionary - NSDictionary* oauthResponse = (NSDictionary *) [response parsedBody:&error]; + NSDictionary *oauthResponse = (NSDictionary *)[response parsedBody:&error]; if ([oauthResponse isKindOfClass:[NSDictionary class]]) { //Check the if an access token comes in the response @@ -96,23 +101,23 @@ - (void)request:(RKRequest *)request didLoadResponse:(RKResponse *)response { if ([errorResponse isEqualToString:@"invalid_grant"]) { errorCode = RKOAuthClientErrorInvalidGrant; } - else if([errorResponse isEqualToString:@"unauthorized_client"]){ + else if ([errorResponse isEqualToString:@"unauthorized_client"]) { errorCode = RKOAuthClientErrorUnauthorizedClient; } - else if([errorResponse isEqualToString:@"invalid_client"]){ + else if ([errorResponse isEqualToString:@"invalid_client"]) { errorCode = RKOAuthClientErrorInvalidClient; } - else if([errorResponse isEqualToString:@"invalid_request"]){ + else if ([errorResponse isEqualToString:@"invalid_request"]) { errorCode = RKOAuthClientErrorInvalidRequest; } - else if([errorResponse isEqualToString:@"unsupported_grant_type"]){ + else if ([errorResponse isEqualToString:@"unsupported_grant_type"]) { errorCode = RKOAuthClientErrorUnsupportedGrantType; } - else if([errorResponse isEqualToString:@"invalid_scope"]){ + else if ([errorResponse isEqualToString:@"invalid_scope"]) { errorCode = RKOAuthClientErrorInvalidScope; } - NSDictionary* userInfo = [NSDictionary dictionaryWithObjectsAndKeys: + NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys: errorDescription, NSLocalizedDescriptionKey, nil]; NSError *error = [NSError errorWithDomain:RKErrorDomain code:errorCode userInfo:userInfo]; @@ -162,8 +167,9 @@ - (void)request:(RKRequest *)request didLoadResponse:(RKResponse *)response { } -- (void)request:(RKRequest *)request didFailLoadWithError:(NSError *)error { - NSDictionary* userInfo = [NSDictionary dictionaryWithObjectsAndKeys: +- (void)request:(RKRequest *)request didFailLoadWithError:(NSError *)error +{ + NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys: error, NSUnderlyingErrorKey, nil]; NSError *clientError = [NSError errorWithDomain:RKErrorDomain code:RKOAuthClientErrorRequestFailure userInfo:userInfo]; if ([self.delegate respondsToSelector:@selector(OAuthClient:didFailLoadingRequest:withError:)]) { diff --git a/Code/Network/RKParams.m b/Code/Network/RKParams.m index 8b90fc8665..196d02d68e 100644 --- a/Code/Network/RKParams.m +++ b/Code/Network/RKParams.m @@ -34,21 +34,24 @@ /** * The boundary used used for multi-part headers */ -NSString* const kRKStringBoundary = @"0xKhTmLbOuNdArY"; +NSString * const kRKStringBoundary = @"0xKhTmLbOuNdArY"; @implementation RKParams -+ (RKParams*)params { - RKParams* params = [[[RKParams alloc] init] autorelease]; ++ (RKParams *)params +{ + RKParams *params = [[[RKParams alloc] init] autorelease]; return params; } -+ (RKParams*)paramsWithDictionary:(NSDictionary*)dictionary { - RKParams* params = [[[RKParams alloc] initWithDictionary:dictionary] autorelease]; ++ (RKParams *)paramsWithDictionary:(NSDictionary *)dictionary +{ + RKParams *params = [[[RKParams alloc] initWithDictionary:dictionary] autorelease]; return params; } -- (id)init { +- (id)init +{ self = [super init]; if (self) { _attachments = [NSMutableArray new]; @@ -59,14 +62,16 @@ - (id)init { return self; } -- (void)dealloc { +- (void)dealloc +{ [_attachments release]; [_footer release]; [super dealloc]; } -- (RKParams *)initWithDictionary:(NSDictionary *)dictionary { +- (RKParams *)initWithDictionary:(NSDictionary *)dictionary +{ self = [self init]; if (self) { // NOTE: We sort the keys to try and ensure given identical dictionaries we'll wind up @@ -81,7 +86,8 @@ - (RKParams *)initWithDictionary:(NSDictionary *)dictionary { return self; } -- (RKParamsAttachment *)setValue:(id )value forParam:(NSString *)param { +- (RKParamsAttachment *)setValue:(id )value forParam:(NSString *)param +{ RKParamsAttachment *attachment = [[RKParamsAttachment alloc] initWithName:param value:value]; [_attachments addObject:attachment]; [attachment release]; @@ -89,7 +95,8 @@ - (RKParamsAttachment *)setValue:(id )value forParam:(NSString *)param return attachment; } -- (NSDictionary *)dictionaryOfPlainTextParams { +- (NSDictionary *)dictionaryOfPlainTextParams +{ NSMutableDictionary *result = [NSMutableDictionary dictionary]; for (RKParamsAttachment *attachment in _attachments) if (attachment.value) // if the value exist, it is plain text param @@ -97,7 +104,8 @@ - (NSDictionary *)dictionaryOfPlainTextParams { return [NSDictionary dictionaryWithDictionary:result]; } -- (RKParamsAttachment *)setFile:(NSString *)filePath forParam:(NSString *)param { +- (RKParamsAttachment *)setFile:(NSString *)filePath forParam:(NSString *)param +{ NSParameterAssert(filePath); NSParameterAssert(param); RKParamsAttachment *attachment = [[RKParamsAttachment alloc] initWithName:param file:filePath]; @@ -107,7 +115,8 @@ - (RKParamsAttachment *)setFile:(NSString *)filePath forParam:(NSString *)param return attachment; } -- (RKParamsAttachment *)setData:(NSData *)data forParam:(NSString *)param { +- (RKParamsAttachment *)setData:(NSData *)data forParam:(NSString *)param +{ NSParameterAssert(data); NSParameterAssert(param); RKParamsAttachment *attachment = [[RKParamsAttachment alloc] initWithName:param data:data]; @@ -117,7 +126,8 @@ - (RKParamsAttachment *)setData:(NSData *)data forParam:(NSString *)param { return attachment; } -- (RKParamsAttachment *)setData:(NSData *)data MIMEType:(NSString *)MIMEType forParam:(NSString *)param { +- (RKParamsAttachment *)setData:(NSData *)data MIMEType:(NSString *)MIMEType forParam:(NSString *)param +{ NSParameterAssert(data); NSParameterAssert(MIMEType); NSParameterAssert(param); @@ -129,7 +139,8 @@ - (RKParamsAttachment *)setData:(NSData *)data MIMEType:(NSString *)MIMEType for return attachment; } -- (RKParamsAttachment *)setData:(NSData *)data MIMEType:(NSString *)MIMEType fileName:(NSString *)fileName forParam:(NSString *)param { +- (RKParamsAttachment *)setData:(NSData *)data MIMEType:(NSString *)MIMEType fileName:(NSString *)fileName forParam:(NSString *)param +{ NSParameterAssert(data); NSParameterAssert(param); RKParamsAttachment *attachment = [self setData:data forParam:param]; @@ -143,7 +154,8 @@ - (RKParamsAttachment *)setData:(NSData *)data MIMEType:(NSString *)MIMEType fil return attachment; } -- (RKParamsAttachment *)setFile:(NSString *)filePath MIMEType:(NSString *)MIMEType fileName:(NSString *)fileName forParam:(NSString *)param { +- (RKParamsAttachment *)setFile:(NSString *)filePath MIMEType:(NSString *)MIMEType fileName:(NSString *)fileName forParam:(NSString *)param +{ NSParameterAssert(filePath); NSParameterAssert(param); RKParamsAttachment *attachment = [self setFile:filePath forParam:param]; @@ -159,21 +171,25 @@ - (RKParamsAttachment *)setFile:(NSString *)filePath MIMEType:(NSString *)MIMETy #pragma mark RKRequestSerializable methods -- (NSString *)HTTPHeaderValueForContentType { +- (NSString *)HTTPHeaderValueForContentType +{ return [NSString stringWithFormat:@"multipart/form-data; boundary=%@", kRKStringBoundary]; } -- (NSUInteger)HTTPHeaderValueForContentLength { +- (NSUInteger)HTTPHeaderValueForContentLength +{ return _length; } -- (void)reset { +- (void)reset +{ _bytesDelivered = 0; _length = 0; _streamStatus = NSStreamStatusNotOpen; } -- (NSInputStream *)HTTPBodyStream { +- (NSInputStream *)HTTPBodyStream +{ // Open each of our attachments [_attachments makeObjectsPerformSelector:@selector(open)]; @@ -183,12 +199,13 @@ - (NSInputStream *)HTTPBodyStream { _length += [attachment length]; } - return (NSInputStream*)self; + return (NSInputStream *)self; } #pragma mark NSInputStream methods -- (NSInteger)read:(uint8_t *)buffer maxLength:(NSUInteger)maxLength { +- (NSInteger)read:(uint8_t *)buffer maxLength:(NSUInteger)maxLength +{ NSUInteger bytesSentInThisRead = 0, bytesRead; NSUInteger lengthOfAttachments = (_length - _footerLength); @@ -224,20 +241,24 @@ - (NSInteger)read:(uint8_t *)buffer maxLength:(NSUInteger)maxLength { return bytesSentInThisRead; } -- (BOOL)getBuffer:(uint8_t **)buffer length:(NSUInteger *)len { +- (BOOL)getBuffer:(uint8_t **)buffer length:(NSUInteger *)len +{ return NO; } -- (BOOL)hasBytesAvailable { +- (BOOL)hasBytesAvailable +{ return _bytesDelivered < _length; } -- (void)open { +- (void)open +{ _streamStatus = NSStreamStatusOpen; RKLogTrace(@"RKParams stream opened..."); } -- (void)close { +- (void)close +{ if (_streamStatus != NSStreamStatusClosed) { _streamStatus = NSStreamStatusClosed; @@ -257,7 +278,8 @@ - (void)close { } } -- (NSStreamStatus)streamStatus { +- (NSStreamStatus)streamStatus +{ if (_streamStatus != NSStreamStatusClosed && _bytesDelivered >= _length) { _streamStatus = NSStreamStatusAtEnd; } @@ -265,11 +287,13 @@ - (NSStreamStatus)streamStatus { return _streamStatus; } -- (NSArray *)attachments { +- (NSArray *)attachments +{ return [NSArray arrayWithArray:_attachments]; } -- (NSString *)MD5 { +- (NSString *)MD5 +{ NSMutableString *attachmentsMD5 = [[NSMutableString new] autorelease]; for (RKParamsAttachment *attachment in self.attachments) { [attachmentsMD5 appendString:[attachment MD5]]; @@ -280,10 +304,12 @@ - (NSString *)MD5 { #pragma mark Core Foundation stream methods -- (void)_scheduleInCFRunLoop:(NSRunLoop *)runLoop forMode:(id)mode { +- (void)_scheduleInCFRunLoop:(NSRunLoop *)runLoop forMode:(id)mode +{ } -- (void)_setCFClientFlags:(CFOptionFlags)flags callback:(CFReadStreamClientCallBack)callback context:(CFStreamClientContext)context { +- (void)_setCFClientFlags:(CFOptionFlags)flags callback:(CFReadStreamClientCallBack)callback context:(CFStreamClientContext)context +{ } @end diff --git a/Code/Network/RKParamsAttachment.h b/Code/Network/RKParamsAttachment.h index 675c1a02cc..9bb2f93708 100644 --- a/Code/Network/RKParamsAttachment.h +++ b/Code/Network/RKParamsAttachment.h @@ -30,12 +30,7 @@ class. */ @interface RKParamsAttachment : NSObject { - NSString *_name; - NSString *_fileName; - NSString *_MIMEType; - @private - NSString *_filePath; NSData *_body; NSInputStream *_bodyStream; NSData *_MIMEHeader; @@ -43,7 +38,6 @@ NSUInteger _bodyLength; NSUInteger _length; NSUInteger _delivered; - id _value; } diff --git a/Code/Network/RKParamsAttachment.m b/Code/Network/RKParamsAttachment.m index e62413f623..2bdea86eb3 100644 --- a/Code/Network/RKParamsAttachment.m +++ b/Code/Network/RKParamsAttachment.m @@ -31,7 +31,7 @@ /** * The multi-part boundary. See RKParams.m */ -extern NSString* const kRKStringBoundary; +extern NSString * const kRKStringBoundary; @implementation RKParamsAttachment @@ -41,7 +41,8 @@ @implementation RKParamsAttachment @synthesize name = _name; @synthesize value = _value; -- (id)initWithName:(NSString *)name { +- (id)initWithName:(NSString *)name +{ self = [self init]; if (self) { self.name = name; @@ -51,10 +52,11 @@ - (id)initWithName:(NSString *)name { return self; } -- (id)initWithName:(NSString *)name value:(id)value { +- (id)initWithName:(NSString *)name value:(id)value +{ if ((self = [self initWithName:name])) { if ([value respondsToSelector:@selector(dataUsingEncoding:)]) { - _body = [[(NSString*)value dataUsingEncoding:NSUTF8StringEncoding] retain]; + _body = [[(NSString *)value dataUsingEncoding:NSUTF8StringEncoding] retain]; } else { _body = [[[NSString stringWithFormat:@"%@", value] dataUsingEncoding:NSUTF8StringEncoding] retain]; } @@ -67,7 +69,8 @@ - (id)initWithName:(NSString *)name value:(id)value { return self; } -- (id)initWithName:(NSString*)name data:(NSData*)data { +- (id)initWithName:(NSString *)name data:(NSData *)data +{ self = [self initWithName:name]; if (self) { _body = [data retain]; @@ -78,7 +81,8 @@ - (id)initWithName:(NSString*)name data:(NSData*)data { return self; } -- (id)initWithName:(NSString*)name file:(NSString*)filePath { +- (id)initWithName:(NSString *)name file:(NSString *)filePath +{ self = [self initWithName:name]; if (self) { NSAssert1([[NSFileManager defaultManager] fileExistsAtPath:filePath], @"Expected file to exist at path: %@", filePath); @@ -89,8 +93,8 @@ - (id)initWithName:(NSString*)name file:(NSString*)filePath { _MIMEType = [MIMEType retain]; _bodyStream = [[NSInputStream alloc] initWithFileAtPath:filePath]; - NSError* error; - NSDictionary* attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:&error]; + NSError *error; + NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:&error]; if (attributes) { _bodyLength = [[attributes objectForKey:NSFileSize] unsignedIntegerValue]; } @@ -102,7 +106,8 @@ - (id)initWithName:(NSString*)name file:(NSString*)filePath { return self; } -- (void)dealloc { +- (void)dealloc +{ [_value release]; [_name release]; [_body release]; @@ -120,13 +125,15 @@ - (void)dealloc { [super dealloc]; } -- (NSString*)MIMEBoundary { +- (NSString *)MIMEBoundary +{ return kRKStringBoundary; } #pragma mark NSStream methods -- (void)open { +- (void)open +{ // Generate the MIME header for this part if (self.fileName && self.MIMEType) { // Typical for file attachments @@ -153,11 +160,13 @@ - (void)open { [_bodyStream open]; } -- (NSUInteger)length { +- (NSUInteger)length +{ return _length; } -- (NSUInteger)read:(uint8_t *)buffer maxLength:(NSUInteger)maxLength { +- (NSUInteger)read:(uint8_t *)buffer maxLength:(NSUInteger)maxLength +{ NSUInteger sent = 0, read; // We are done with the read @@ -194,19 +203,20 @@ - (NSUInteger)read:(uint8_t *)buffer maxLength:(NSUInteger)maxLength { if (_delivered >= (_length - 2) && sent < maxLength) { if (_delivered == (_length - 2)) { *(buffer + sent) = '\r'; - sent ++; - _delivered ++; + sent++; + _delivered++; } *(buffer + sent) = '\n'; - sent ++; - _delivered ++; + sent++; + _delivered++; } return sent; } -- (NSString *)MD5 { +- (NSString *)MD5 +{ if (_body) { return [_body MD5]; } else if (_filePath) { diff --git a/Code/Network/RKReachabilityObserver.h b/Code/Network/RKReachabilityObserver.h index 390d71a812..be613cccd7 100755 --- a/Code/Network/RKReachabilityObserver.h +++ b/Code/Network/RKReachabilityObserver.h @@ -75,11 +75,7 @@ typedef enum { code sample: http://developer.apple.com/library/ios/#samplecode/Reachability/Listings/Classes_Reachability_m.html */ @interface RKReachabilityObserver : NSObject { - NSString *_host; SCNetworkReachabilityRef _reachabilityRef; - BOOL _reachabilityDetermined; - BOOL _monitoringLocalWiFi; - SCNetworkReachabilityFlags _reachabilityFlags; } ///----------------------------------------------------------------------------- diff --git a/Code/Network/RKReachabilityObserver.m b/Code/Network/RKReachabilityObserver.m index b2956f57f2..5afef62b80 100755 --- a/Code/Network/RKReachabilityObserver.m +++ b/Code/Network/RKReachabilityObserver.m @@ -43,14 +43,14 @@ - (void)unscheduleObserver; @end // Constants -NSString* const RKReachabilityDidChangeNotification = @"RKReachabilityDidChangeNotification"; -NSString* const RKReachabilityFlagsUserInfoKey = @"RKReachabilityFlagsUserInfoKey"; -NSString* const RKReachabilityWasDeterminedNotification = @"RKReachabilityWasDeterminedNotification"; +NSString * const RKReachabilityDidChangeNotification = @"RKReachabilityDidChangeNotification"; +NSString * const RKReachabilityFlagsUserInfoKey = @"RKReachabilityFlagsUserInfoKey"; +NSString * const RKReachabilityWasDeterminedNotification = @"RKReachabilityWasDeterminedNotification"; static void ReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkReachabilityFlags flags, void *info) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - RKReachabilityObserver *observer = (RKReachabilityObserver *) info; + RKReachabilityObserver *observer = (RKReachabilityObserver *)info; observer.reachabilityFlags = flags; [pool release]; @@ -65,11 +65,13 @@ @implementation RKReachabilityObserver @synthesize reachabilityDetermined = _reachabilityDetermined; @synthesize monitoringLocalWiFi = _monitoringLocalWiFi; -+ (RKReachabilityObserver *)reachabilityObserverForAddress:(const struct sockaddr *)address { ++ (RKReachabilityObserver *)reachabilityObserverForAddress:(const struct sockaddr *)address +{ return [[[self alloc] initWithAddress:address] autorelease]; } -+ (RKReachabilityObserver *)reachabilityObserverForInternetAddress:(in_addr_t)internetAddress { ++ (RKReachabilityObserver *)reachabilityObserverForInternetAddress:(in_addr_t)internetAddress +{ struct sockaddr_in address; bzero(&address, sizeof(address)); address.sin_len = sizeof(address); @@ -78,19 +80,23 @@ + (RKReachabilityObserver *)reachabilityObserverForInternetAddress:(in_addr_t)in return [self reachabilityObserverForAddress:(struct sockaddr *)&address]; } -+ (RKReachabilityObserver *)reachabilityObserverForInternet { ++ (RKReachabilityObserver *)reachabilityObserverForInternet +{ return [self reachabilityObserverForInternetAddress:INADDR_ANY]; } -+ (RKReachabilityObserver *)reachabilityObserverForLocalWifi { ++ (RKReachabilityObserver *)reachabilityObserverForLocalWifi +{ return [self reachabilityObserverForInternetAddress:IN_LINKLOCALNETNUM]; } -+ (RKReachabilityObserver *)reachabilityObserverForHost:(NSString *)hostNameOrIPAddress { ++ (RKReachabilityObserver *)reachabilityObserverForHost:(NSString *)hostNameOrIPAddress +{ return [[[self alloc] initWithHost:hostNameOrIPAddress] autorelease]; } -- (id)initWithAddress:(const struct sockaddr *)address { +- (id)initWithAddress:(const struct sockaddr *)address +{ self = [super init]; if (self) { _reachabilityRef = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, address); @@ -130,10 +136,11 @@ - (id)initWithAddress:(const struct sockaddr *)address { return self; } -- (id)initWithHost:(NSString *)hostNameOrIPAddress { +- (id)initWithHost:(NSString *)hostNameOrIPAddress +{ // Determine if the string contains a hostname or IP address struct sockaddr_in sa; - char *hostNameOrIPAddressCString = (char *) [hostNameOrIPAddress UTF8String]; + char *hostNameOrIPAddressCString = (char *)[hostNameOrIPAddress UTF8String]; int result = inet_pton(AF_INET, hostNameOrIPAddressCString, &(sa.sin_addr)); if (result != 0) { // IP Address @@ -144,7 +151,7 @@ - (id)initWithHost:(NSString *)hostNameOrIPAddress { remote_saddr.sin_family = AF_INET; inet_aton(hostNameOrIPAddressCString, &(remote_saddr.sin_addr)); - return [self initWithAddress:(struct sockaddr *) &remote_saddr]; + return [self initWithAddress:(struct sockaddr *)&remote_saddr]; } // Hostname @@ -165,7 +172,8 @@ - (id)initWithHost:(NSString *)hostNameOrIPAddress { return self; } -- (void)dealloc { +- (void)dealloc +{ RKLogTrace(@"Deallocating reachability observer %@", self); [[NSNotificationCenter defaultCenter] removeObserver:self]; @@ -178,14 +186,16 @@ - (void)dealloc { [super dealloc]; } -- (BOOL)getFlags { +- (BOOL)getFlags +{ SCNetworkReachabilityFlags flags = 0; BOOL result = SCNetworkReachabilityGetFlags(_reachabilityRef, &flags); if (result) self.reachabilityFlags = flags; return result; } -- (NSString *)stringFromNetworkStatus:(RKReachabilityNetworkStatus)status { +- (NSString *)stringFromNetworkStatus:(RKReachabilityNetworkStatus)status +{ switch (status) { case RKReachabilityIndeterminate: return @"RKReachabilityIndeterminate"; @@ -210,7 +220,8 @@ - (NSString *)stringFromNetworkStatus:(RKReachabilityNetworkStatus)status { return nil; } -- (NSString *)reachabilityFlagsDescription { +- (NSString *)reachabilityFlagsDescription +{ return [NSString stringWithFormat:@"%c%c %c%c%c%c%c%c%c", #if TARGET_OS_IPHONE (_reachabilityFlags & kSCNetworkReachabilityFlagsIsWWAN) ? 'W' : '-', @@ -228,7 +239,8 @@ - (NSString *)reachabilityFlagsDescription { (_reachabilityFlags & kSCNetworkReachabilityFlagsIsDirect) ? 'd' : '-']; } -- (RKReachabilityNetworkStatus)networkStatus { +- (RKReachabilityNetworkStatus)networkStatus +{ NSAssert(_reachabilityRef != NULL, @"currentNetworkStatus called with NULL reachabilityRef"); RKReachabilityNetworkStatus status = RKReachabilityNotReachable; @@ -286,19 +298,22 @@ - (RKReachabilityNetworkStatus)networkStatus { #pragma Reachability Flag Introspection -- (void)validateIntrospection { +- (void)validateIntrospection +{ NSAssert(_reachabilityRef != NULL, @"connectionRequired called with NULL reachabilityRef"); NSAssert(self.isReachabilityDetermined, @"Cannot inspect reachability state: no reachabilityFlags available. Be sure to check isReachabilityDetermined"); } -- (BOOL)isNetworkReachable { +- (BOOL)isNetworkReachable +{ [self validateIntrospection]; BOOL reachable = (RKReachabilityNotReachable != [self networkStatus]); RKLogDebug(@"Reachability observer %@ determined isNetworkReachable = %d", self, reachable); return reachable; } -- (BOOL)isConnectionRequired { +- (BOOL)isConnectionRequired +{ [self validateIntrospection]; BOOL required = (_reachabilityFlags & kSCNetworkReachabilityFlagsConnectionRequired); @@ -306,17 +321,20 @@ - (BOOL)isConnectionRequired { return required; } -- (BOOL)isReachableViaWWAN { +- (BOOL)isReachableViaWWAN +{ [self validateIntrospection]; return self.networkStatus == RKReachabilityReachableViaWWAN; } -- (BOOL)isReachableViaWiFi { +- (BOOL)isReachableViaWiFi +{ [self validateIntrospection]; return self.networkStatus == RKReachabilityReachableViaWiFi; } -- (BOOL)isConnectionOnDemand { +- (BOOL)isConnectionOnDemand +{ [self validateIntrospection]; return ((_reachabilityFlags & kSCNetworkReachabilityFlagsConnectionRequired) && (_reachabilityFlags & (kSCNetworkReachabilityFlagsConnectionOnTraffic | @@ -324,7 +342,8 @@ - (BOOL)isConnectionOnDemand { } -- (BOOL)isInterventionRequired { +- (BOOL)isInterventionRequired +{ [self validateIntrospection]; return ((_reachabilityFlags & kSCNetworkReachabilityFlagsConnectionRequired) && (_reachabilityFlags & kSCNetworkReachabilityFlagsInterventionRequired)); @@ -332,7 +351,8 @@ - (BOOL)isInterventionRequired { #pragma mark Observer scheduling -- (void)scheduleObserver { +- (void)scheduleObserver +{ SCNetworkReachabilityContext context = { .info = self }; RKLogDebug(@"Scheduling reachability observer %@ in main dispatch queue", self); if (! SCNetworkReachabilitySetCallback(_reachabilityRef, ReachabilityCallback, &context)) { @@ -346,7 +366,8 @@ - (void)scheduleObserver { } } -- (void)unscheduleObserver { +- (void)unscheduleObserver +{ if (_reachabilityRef) { RKLogDebug(@"%@: Unscheduling reachability observer from main dispatch queue", self); if (! SCNetworkReachabilitySetDispatchQueue(_reachabilityRef, NULL)) { @@ -358,7 +379,8 @@ - (void)unscheduleObserver { } } -- (void)setReachabilityFlags:(SCNetworkReachabilityFlags)reachabilityFlags { +- (void)setReachabilityFlags:(SCNetworkReachabilityFlags)reachabilityFlags +{ // Save the reachability flags _reachabilityFlags = reachabilityFlags; @@ -374,8 +396,9 @@ - (void)setReachabilityFlags:(SCNetworkReachabilityFlags)reachabilityFlags { [[NSNotificationCenter defaultCenter] postNotificationName:RKReachabilityDidChangeNotification object:self userInfo:userInfo]; } -- (NSString *)description { - return [NSString stringWithFormat:@"<%@: %p host=%@ isReachabilityDetermined=%@ isMonitoringLocalWiFi=%d reachabilityFlags=%@>", +- (NSString *)description +{ + return [NSString stringWithFormat:@"<%@: %p host=%@ isReachabilityDetermined=%@ isMonitoringLocalWiFi=%@ reachabilityFlags=%@>", NSStringFromClass([self class]), self, self.host, self.isReachabilityDetermined ? @"YES" : @"NO", self.isMonitoringLocalWiFi ? @"YES" : @"NO", [self reachabilityFlagsDescription]]; } diff --git a/Code/Network/RKRequest.h b/Code/Network/RKRequest.h index b81ac5d8a2..215a5edca8 100644 --- a/Code/Network/RKRequest.h +++ b/Code/Network/RKRequest.h @@ -167,11 +167,6 @@ typedef void(^RKRequestDidFailLoadWithErrorBlock)(NSError *error); RKRequestDidLoadResponseBlock _onDidLoadResponse; RKRequestDidFailLoadWithErrorBlock _onDidFailLoadWithError; - -#if TARGET_OS_IPHONE - RKRequestBackgroundPolicy _backgroundPolicy; - UIBackgroundTaskIdentifier _backgroundTaskIdentifier; -#endif } ///----------------------------------------------------------------------------- @@ -621,7 +616,7 @@ typedef void(^RKRequestDidFailLoadWithErrorBlock)(NSError *error); @return YES if the request was sent a cancel message, otherwise NO. */ -@property(nonatomic, assign, readonly, getter=isCancelled) BOOL cancelled; +@property (nonatomic, assign, readonly, getter=isCancelled) BOOL cancelled; /** Cancels the underlying URL connection. diff --git a/Code/Network/RKRequest.m b/Code/Network/RKRequest.m index 3cd1089647..2f2e617f67 100644 --- a/Code/Network/RKRequest.m +++ b/Code/Network/RKRequest.m @@ -135,11 +135,13 @@ @implementation RKRequest @synthesize backgroundTaskIdentifier = _backgroundTaskIdentifier; #endif -+ (RKRequest*)requestWithURL:(NSURL*)URL { ++ (RKRequest *)requestWithURL:(NSURL *)URL +{ return [[[RKRequest alloc] initWithURL:URL] autorelease]; } -- (id)initWithURL:(NSURL*)URL { +- (id)initWithURL:(NSURL *)URL +{ self = [self init]; if (self) { _URL = [URL retain]; @@ -154,7 +156,8 @@ - (id)initWithURL:(NSURL*)URL { return self; } -- (id)init { +- (id)init +{ self = [super init]; if (self) { self.runLoopMode = NSRunLoopCommonModes; @@ -171,7 +174,8 @@ - (id)init { return self; } -- (void)reset { +- (void)reset +{ if (self.isLoading) { RKLogWarning(@"Request was reset while loading: %@. Canceling.", self); [self cancel]; @@ -186,14 +190,15 @@ - (void)reset { self.cancelled = NO; } -- (void)cleanupBackgroundTask { +- (void)cleanupBackgroundTask +{ #if TARGET_OS_IPHONE BOOL backgroundOK = &UIBackgroundTaskInvalid != NULL; if (backgroundOK && UIBackgroundTaskInvalid == self.backgroundTaskIdentifier) { return; } - UIApplication* app = [UIApplication sharedApplication]; + UIApplication *app = [UIApplication sharedApplication]; if ([app respondsToSelector:@selector(beginBackgroundTaskWithExpirationHandler:)]) { [app endBackgroundTask:_backgroundTaskIdentifier]; _backgroundTaskIdentifier = UIBackgroundTaskInvalid; @@ -201,7 +206,8 @@ - (void)cleanupBackgroundTask { #endif } -- (void)dealloc { +- (void)dealloc +{ [[NSNotificationCenter defaultCenter] removeObserver:self]; self.delegate = nil; @@ -261,11 +267,13 @@ - (void)dealloc { [super dealloc]; } -- (BOOL)shouldSendParams { +- (BOOL)shouldSendParams +{ return (_params && (_method != RKRequestMethodGET && _method != RKRequestMethodHEAD)); } -- (void)setRequestBody { +- (void)setRequestBody +{ if ([self shouldSendParams]) { // Prefer the use of a stream over a raw body if ([_params respondsToSelector:@selector(HTTPBodyStream)]) { @@ -278,23 +286,28 @@ - (void)setRequestBody { } } -- (NSData*)HTTPBody { +- (NSData *)HTTPBody +{ return self.URLRequest.HTTPBody; } -- (void)setHTTPBody:(NSData *)HTTPBody { +- (void)setHTTPBody:(NSData *)HTTPBody +{ [self.URLRequest setHTTPBody:HTTPBody]; } -- (NSString*)HTTPBodyString { +- (NSString *)HTTPBodyString +{ return [[[NSString alloc] initWithData:self.URLRequest.HTTPBody encoding:NSASCIIStringEncoding] autorelease]; } -- (void)setHTTPBodyString:(NSString *)HTTPBodyString { +- (void)setHTTPBodyString:(NSString *)HTTPBodyString +{ [self.URLRequest setHTTPBody:[HTTPBodyString dataUsingEncoding:NSASCIIStringEncoding]]; } -- (void)addHeadersToRequest { +- (void)addHeadersToRequest +{ NSString *header = nil; for (header in _additionalHTTPHeaders) { [_URLRequest setValue:[_additionalHTTPHeaders valueForKey:header] forHTTPHeaderField:header]; @@ -318,7 +331,7 @@ - (void)addHeadersToRequest { if (self.authenticationType == RKRequestAuthenticationTypeHTTPBasic && _username && _password) { CFHTTPMessageRef dummyRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, (CFStringRef)[self HTTPMethod], (CFURLRef)[self URL], kCFHTTPVersion1_1); if (dummyRequest) { - CFHTTPMessageAddAuthentication(dummyRequest, nil, (CFStringRef)_username, (CFStringRef)_password,kCFHTTPAuthenticationSchemeBasic, FALSE); + CFHTTPMessageAddAuthentication(dummyRequest, nil, (CFStringRef)_username, (CFStringRef)_password, kCFHTTPAuthenticationSchemeBasic, FALSE); CFStringRef authorizationString = CFHTTPMessageCopyHeaderFieldValue(dummyRequest, CFSTR("Authorization")); if (authorizationString) { [_URLRequest setValue:(NSString *)authorizationString forHTTPHeaderField:@"Authorization"]; @@ -330,7 +343,7 @@ - (void)addHeadersToRequest { // Add OAuth headers if necessary // OAuth 1 - if(self.authenticationType == RKRequestAuthenticationTypeOAuth1){ + if (self.authenticationType == RKRequestAuthenticationTypeOAuth1) { NSURLRequest *echo = nil; // use the suitable parameters dict @@ -339,47 +352,30 @@ - (void)addHeadersToRequest { parameters = [(RKParams *)self.params dictionaryOfPlainTextParams]; else parameters = [_URL queryParameters]; - - if (self.method == RKRequestMethodPUT) - echo = [GCOAuth URLRequestForPath:[_URL path] - PUTParameters:parameters - scheme:[_URL scheme] - host:[_URL hostAndPort] - consumerKey:self.OAuth1ConsumerKey - consumerSecret:self.OAuth1ConsumerSecret - accessToken:self.OAuth1AccessToken - tokenSecret:self.OAuth1AccessTokenSecret]; - else if (self.method == RKRequestMethodPOST) - echo = [GCOAuth URLRequestForPath:[_URL path] - POSTParameters:parameters - scheme:[_URL scheme] - host:[_URL hostAndPort] - consumerKey:self.OAuth1ConsumerKey - consumerSecret:self.OAuth1ConsumerSecret - accessToken:self.OAuth1AccessToken - tokenSecret:self.OAuth1AccessTokenSecret]; - else - echo = [GCOAuth URLRequestForPath:[_URL path] - GETParameters:[_URL queryParameters] - scheme:[_URL scheme] - host:[_URL hostAndPort] - consumerKey:self.OAuth1ConsumerKey - consumerSecret:self.OAuth1ConsumerSecret - accessToken:self.OAuth1AccessToken - tokenSecret:self.OAuth1AccessTokenSecret]; + + NSString *methodString = RKRequestMethodNameFromType(self.method); + echo = [GCOAuth URLRequestForPath:[_URL path] + HTTPMethod:methodString + parameters:(self.method == RKRequestMethodGET) ? [_URL queryParameters] : parameters + scheme:[_URL scheme] + host:[_URL host] + consumerKey:self.OAuth1ConsumerKey + consumerSecret:self.OAuth1ConsumerSecret + accessToken:self.OAuth1AccessToken + tokenSecret:self.OAuth1AccessTokenSecret]; [_URLRequest setValue:[echo valueForHTTPHeaderField:@"Authorization"] forHTTPHeaderField:@"Authorization"]; [_URLRequest setValue:[echo valueForHTTPHeaderField:@"Accept-Encoding"] forHTTPHeaderField:@"Accept-Encoding"]; [_URLRequest setValue:[echo valueForHTTPHeaderField:@"User-Agent"] forHTTPHeaderField:@"User-Agent"]; } // OAuth 2 valid request - if(self.authenticationType == RKRequestAuthenticationTypeOAuth2) { - NSString *authorizationString = [NSString stringWithFormat:@"OAuth2 %@",self.OAuth2AccessToken]; + if (self.authenticationType == RKRequestAuthenticationTypeOAuth2) { + NSString *authorizationString = [NSString stringWithFormat:@"OAuth2 %@", self.OAuth2AccessToken]; [_URLRequest setValue:authorizationString forHTTPHeaderField:@"Authorization"]; } if (self.cachePolicy & RKRequestCachePolicyEtag) { - NSString* etag = [self.cache etagForRequest:self]; + NSString *etag = [self.cache etagForRequest:self]; if (etag) { RKLogTrace(@"Setting If-None-Match header to '%@'", etag); [_URLRequest setValue:etag forHTTPHeaderField:@"If-None-Match"]; @@ -388,7 +384,8 @@ - (void)addHeadersToRequest { } // Setup the NSURLRequest. The request must be prepared right before dispatching -- (BOOL)prepareURLRequest { +- (BOOL)prepareURLRequest +{ [_URLRequest setHTTPMethod:[self HTTPMethod]]; if ([self.delegate respondsToSelector:@selector(requestWillPrepareForSend:)]) { @@ -398,14 +395,15 @@ - (BOOL)prepareURLRequest { [self setRequestBody]; [self addHeadersToRequest]; - NSString* body = [[NSString alloc] initWithData:[_URLRequest HTTPBody] encoding:NSUTF8StringEncoding]; + NSString *body = [[NSString alloc] initWithData:[_URLRequest HTTPBody] encoding:NSUTF8StringEncoding]; RKLogTrace(@"Prepared %@ URLRequest '%@'. HTTP Headers: %@. HTTP Body: %@.", [self HTTPMethod], _URLRequest, [_URLRequest allHTTPHeaderFields], body); [body release]; return YES; } -- (void)cancelAndInformDelegate:(BOOL)informDelegate { +- (void)cancelAndInformDelegate:(BOOL)informDelegate +{ self.cancelled = YES; [_connection cancel]; [_connection release]; @@ -418,12 +416,14 @@ - (void)cancelAndInformDelegate:(BOOL)informDelegate { } } -- (NSString *)HTTPMethod { +- (NSString *)HTTPMethod +{ return RKRequestMethodNameFromType(self.method); } // NOTE: We could factor the knowledge about the queue out of RKRequest entirely, but it will break behavior. -- (void)send { +- (void)send +{ NSAssert(NO == self.isLoading || NO == self.isLoaded, @"Cannot send a request that is loading or loaded without resetting it first."); if (self.queue) { [self.queue addRequest:self]; @@ -432,7 +432,8 @@ - (void)send { } } -- (void)fireAsynchronousRequest { +- (void)fireAsynchronousRequest +{ RKLogDebug(@"Sending asynchronous %@ request to URL %@.", [self HTTPMethod], [[self URL] absoluteString]); if (![self prepareURLRequest]) { RKLogWarning(@"Failed to send request asynchronously: prepareURLRequest returned NO."); @@ -445,7 +446,7 @@ - (void)fireAsynchronousRequest { [self.delegate requestDidStartLoad:self]; } - RKResponse* response = [[[RKResponse alloc] initWithRequest:self] autorelease]; + RKResponse *response = [[[RKResponse alloc] initWithRequest:self] autorelease]; _connection = [[[[NSURLConnection alloc] initWithRequest:_URLRequest delegate:response startImmediately:NO] autorelease] retain]; [_connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:self.runLoopMode]; @@ -454,13 +455,14 @@ - (void)fireAsynchronousRequest { [[NSNotificationCenter defaultCenter] postNotificationName:RKRequestSentNotification object:self userInfo:nil]; } -- (BOOL)shouldLoadFromCache { +- (BOOL)shouldLoadFromCache +{ // if RKRequestCachePolicyEnabled or if RKRequestCachePolicyTimeout and we are in the timeout if ([self.cache hasResponseForRequest:self]) { if (self.cachePolicy & RKRequestCachePolicyEnabled) { return YES; } else if (self.cachePolicy & RKRequestCachePolicyTimeout) { - NSDate* date = [self.cache cacheDateForRequest:self]; + NSDate *date = [self.cache cacheDateForRequest:self]; NSTimeInterval interval = [[NSDate date] timeIntervalSinceDate:date]; return interval <= self.cacheTimeoutInterval; } @@ -468,12 +470,14 @@ - (BOOL)shouldLoadFromCache { return NO; } -- (RKResponse*)loadResponseFromCache { +- (RKResponse *)loadResponseFromCache +{ RKLogDebug(@"Found cached content, loading..."); return [self.cache responseForRequest:self]; } -- (BOOL)shouldDispatchRequest { +- (BOOL)shouldDispatchRequest +{ if (nil == self.reachabilityObserver || NO == [self.reachabilityObserver isReachabilityDetermined]) { return YES; } @@ -481,18 +485,19 @@ - (BOOL)shouldDispatchRequest { return [self.reachabilityObserver isNetworkReachable]; } -- (void)sendAsynchronously { +- (void)sendAsynchronously +{ NSAssert(NO == self.loading || NO == self.loaded, @"Cannot send a request that is loading or loaded without resetting it first."); _sentSynchronously = NO; if ([self shouldLoadFromCache]) { - RKResponse* response = [self loadResponseFromCache]; + RKResponse *response = [self loadResponseFromCache]; self.loading = YES; [self performSelector:@selector(didFinishLoad:) withObject:response afterDelay:0]; } else if ([self shouldDispatchRequest]) { [self createTimeoutTimer]; #if TARGET_OS_IPHONE // Background Request Policy support - UIApplication* app = [UIApplication sharedApplication]; + UIApplication *app = [UIApplication sharedApplication]; if (self.backgroundPolicy == RKRequestBackgroundPolicyNone || NO == [app respondsToSelector:@selector(beginBackgroundTaskWithExpirationHandler:)]) { // No support for background (iOS 3.x) or the policy is none -- just fire the request @@ -508,7 +513,7 @@ - (void)sendAsynchronously { RKLogInfo(@"Beginning background task to perform processing..."); // Fork a background task for continueing a long-running request - __block RKRequest* weakSelf = self; + __block RKRequest *weakSelf = self; __block id weakDelegate = _delegate; _backgroundTaskIdentifier = [app beginBackgroundTaskWithExpirationHandler:^{ RKLogInfo(@"Background request time expired, canceling request."); @@ -538,22 +543,23 @@ - (void)sendAsynchronously { self.loading = YES; RKLogError(@"Failed to send request to %@ due to unreachable network. Reachability observer = %@", [[self URL] absoluteString], self.reachabilityObserver); - NSString* errorMessage = [NSString stringWithFormat:@"The client is unable to contact the resource at %@", [[self URL] absoluteString]]; + NSString *errorMessage = [NSString stringWithFormat:@"The client is unable to contact the resource at %@", [[self URL] absoluteString]]; NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys: errorMessage, NSLocalizedDescriptionKey, nil]; - NSError* error = [NSError errorWithDomain:RKErrorDomain code:RKRequestBaseURLOfflineError userInfo:userInfo]; + NSError *error = [NSError errorWithDomain:RKErrorDomain code:RKRequestBaseURLOfflineError userInfo:userInfo]; [self performSelector:@selector(didFailLoadWithError:) withObject:error afterDelay:0]; } } } -- (RKResponse*)sendSynchronously { +- (RKResponse *)sendSynchronously +{ NSAssert(NO == self.loading || NO == self.loaded, @"Cannot send a request that is loading or loaded without resetting it first."); - NSHTTPURLResponse* URLResponse = nil; - NSError* error; - NSData* payload = nil; - RKResponse* response = nil; + NSHTTPURLResponse *URLResponse = nil; + NSError *error; + NSData *payload = nil; + RKResponse *response = nil; _sentSynchronously = YES; if ([self shouldLoadFromCache]) { @@ -597,7 +603,7 @@ - (RKResponse*)sendSynchronously { response = [self loadResponseFromCache]; } else { - NSString* errorMessage = [NSString stringWithFormat:@"The client is unable to contact the resource at %@", [[self URL] absoluteString]]; + NSString *errorMessage = [NSString stringWithFormat:@"The client is unable to contact the resource at %@", [[self URL] absoluteString]]; NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys: errorMessage, NSLocalizedDescriptionKey, nil]; @@ -610,31 +616,36 @@ - (RKResponse*)sendSynchronously { return response; } -- (void)cancel { +- (void)cancel +{ [self cancelAndInformDelegate:YES]; } -- (void)createTimeoutTimer { +- (void)createTimeoutTimer +{ _timeoutTimer = [NSTimer scheduledTimerWithTimeInterval:self.timeoutInterval target:self selector:@selector(timeout) userInfo:nil repeats:NO]; } -- (void)timeout { +- (void)timeout +{ [self cancelAndInformDelegate:NO]; RKLogError(@"Failed to send request to %@ due to connection timeout. Timeout interval = %f", [[self URL] absoluteString], self.timeoutInterval); - NSString* errorMessage = [NSString stringWithFormat:@"The client timed out connecting to the resource at %@", [[self URL] absoluteString]]; + NSString *errorMessage = [NSString stringWithFormat:@"The client timed out connecting to the resource at %@", [[self URL] absoluteString]]; NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys: errorMessage, NSLocalizedDescriptionKey, nil]; - NSError* error = [NSError errorWithDomain:RKErrorDomain code:RKRequestConnectionTimeoutError userInfo:userInfo]; + NSError *error = [NSError errorWithDomain:RKErrorDomain code:RKRequestConnectionTimeoutError userInfo:userInfo]; [self didFailLoadWithError:error]; } -- (void)invalidateTimeoutTimer { +- (void)invalidateTimeoutTimer +{ [_timeoutTimer invalidate]; _timeoutTimer = nil; } -- (void)didFailLoadWithError:(NSError*)error { +- (void)didFailLoadWithError:(NSError *)error +{ if (_cachePolicy & RKRequestCachePolicyLoadOnError && [self.cache hasResponseForRequest:self]) { @@ -652,7 +663,7 @@ - (void)didFailLoadWithError:(NSError*)error { } - NSDictionary* userInfo = [NSDictionary dictionaryWithObject:error forKey:RKRequestDidFailWithErrorNotificationUserInfoErrorKey]; + NSDictionary *userInfo = [NSDictionary dictionaryWithObject:error forKey:RKRequestDidFailWithErrorNotificationUserInfoErrorKey]; [[NSNotificationCenter defaultCenter] postNotificationName:RKRequestDidFailWithErrorNotification object:self userInfo:userInfo]; @@ -663,17 +674,19 @@ - (void)didFailLoadWithError:(NSError*)error { [[NSNotificationCenter defaultCenter] postNotificationName:RKRequestDidFinishLoadingNotification object:self]; } -- (void)updateInternalCacheDate { - NSDate* date = [NSDate date]; +- (void)updateInternalCacheDate +{ + NSDate *date = [NSDate date]; RKLogInfo(@"Updating cache date for request %@ to %@", self, date); [self.cache setCacheDate:date forRequest:self]; } -- (void)didFinishLoad:(RKResponse *)response { +- (void)didFinishLoad:(RKResponse *)response +{ self.loading = NO; self.loaded = YES; - RKLogInfo(@"Status Code: %ld", (long) [response statusCode]); + RKLogInfo(@"Status Code: %ld", (long)[response statusCode]); RKLogDebug(@"Body: %@", [response bodyAsString]); self.response = response; @@ -699,7 +712,7 @@ - (void)didFinishLoad:(RKResponse *)response { [[NSNotificationCenter defaultCenter] postNotificationName:RKServiceDidBecomeUnavailableNotification object:self]; } - NSDictionary* userInfo = [NSDictionary dictionaryWithObject:self.response + NSDictionary *userInfo = [NSDictionary dictionaryWithObject:self.response forKey:RKRequestDidLoadResponseNotificationUserInfoResponseKey]; [[NSNotificationCenter defaultCenter] postNotificationName:RKRequestDidLoadResponseNotification object:self @@ -710,47 +723,56 @@ - (void)didFinishLoad:(RKResponse *)response { [[NSNotificationCenter defaultCenter] postNotificationName:RKRequestDidFinishLoadingNotification object:self]; } -- (BOOL)isGET { +- (BOOL)isGET +{ return _method == RKRequestMethodGET; } -- (BOOL)isPOST { +- (BOOL)isPOST +{ return _method == RKRequestMethodPOST; } -- (BOOL)isPUT { +- (BOOL)isPUT +{ return _method == RKRequestMethodPUT; } -- (BOOL)isDELETE { +- (BOOL)isDELETE +{ return _method == RKRequestMethodDELETE; } -- (BOOL)isHEAD { +- (BOOL)isHEAD +{ return _method == RKRequestMethodHEAD; } -- (BOOL)isUnsent { +- (BOOL)isUnsent +{ return self.loading == NO && self.loaded == NO; } -- (NSString*)resourcePath { - NSString* resourcePath = nil; +- (NSString *)resourcePath +{ + NSString *resourcePath = nil; if ([self.URL isKindOfClass:[RKURL class]]) { - RKURL* url = (RKURL*)self.URL; + RKURL *url = (RKURL *)self.URL; resourcePath = url.resourcePath; } return resourcePath; } -- (void)setURL:(NSURL *)URL { +- (void)setURL:(NSURL *)URL +{ [URL retain]; [_URL release]; _URL = URL; _URLRequest.URL = URL; } -- (void)setResourcePath:(NSString *)resourcePath { +- (void)setResourcePath:(NSString *)resourcePath +{ if ([self.URL isKindOfClass:[RKURL class]]) { self.URL = [(RKURL *)self.URL URLByReplacingResourcePath:resourcePath]; } else { @@ -758,15 +780,18 @@ - (void)setResourcePath:(NSString *)resourcePath { } } -- (BOOL)wasSentToResourcePath:(NSString*)resourcePath { +- (BOOL)wasSentToResourcePath:(NSString *)resourcePath +{ return [[self resourcePath] isEqualToString:resourcePath]; } -- (BOOL)wasSentToResourcePath:(NSString *)resourcePath method:(RKRequestMethod)method { +- (BOOL)wasSentToResourcePath:(NSString *)resourcePath method:(RKRequestMethod)method +{ return (self.method == method && [self wasSentToResourcePath:resourcePath]); } -- (void)appDidEnterBackgroundNotification:(NSNotification*)notification { +- (void)appDidEnterBackgroundNotification:(NSNotification *)notification +{ #if TARGET_OS_IPHONE [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil]; if (self.backgroundPolicy == RKRequestBackgroundPolicyCancel) { @@ -779,17 +804,19 @@ - (void)appDidEnterBackgroundNotification:(NSNotification*)notification { #endif } -- (BOOL)isCacheable { +- (BOOL)isCacheable +{ return _method == RKRequestMethodGET; } -- (NSString*)cacheKey { +- (NSString *)cacheKey +{ if (! [self isCacheable]) { return nil; } // Use [_params HTTPBody] because the URLRequest body may not have been set up yet. - NSString* compositeCacheKey = nil; + NSString *compositeCacheKey = nil; if (_params) { if ([_params respondsToSelector:@selector(HTTPBody)]) { compositeCacheKey = [NSString stringWithFormat:@"%@-%d-%@", self.URL, _method, [_params HTTPBody]]; @@ -803,11 +830,12 @@ - (NSString*)cacheKey { return [compositeCacheKey MD5]; } -- (void)setBody:(NSDictionary *)body forMIMEType:(NSString *)MIMEType { +- (void)setBody:(NSDictionary *)body forMIMEType:(NSString *)MIMEType +{ id parser = [[RKParserRegistry sharedRegistry] parserForMIMEType:MIMEType]; NSError *error = nil; - NSString* parsedValue = [parser stringFromObject:body error:&error]; + NSString *parsedValue = [parser stringFromObject:body error:&error]; RKLogTrace(@"parser=%@, error=%@, parsedValue=%@", parser, error, parsedValue); @@ -818,11 +846,13 @@ - (void)setBody:(NSDictionary *)body forMIMEType:(NSString *)MIMEType { } // Deprecations -+ (RKRequest*)requestWithURL:(NSURL*)URL delegate:(id)delegate { ++ (RKRequest *)requestWithURL:(NSURL *)URL delegate:(id)delegate +{ return [[[RKRequest alloc] initWithURL:URL delegate:delegate] autorelease]; } -- (id)initWithURL:(NSURL*)URL delegate:(id)delegate { +- (id)initWithURL:(NSURL *)URL delegate:(id)delegate +{ self = [self initWithURL:URL]; if (self) { _delegate = delegate; diff --git a/Code/Network/RKRequestCache.m b/Code/Network/RKRequestCache.m index d0d376ed0e..d6a94b72b8 100644 --- a/Code/Network/RKRequestCache.m +++ b/Code/Network/RKRequestCache.m @@ -33,13 +33,14 @@ NSString * const RKRequestCacheMIMETypeHeadersKey = @"X-RESTKIT-CACHED-MIME-TYPE"; NSString * const RKRequestCacheURLHeadersKey = @"X-RESTKIT-CACHED-URL"; -static NSDateFormatter* __rfc1123DateFormatter; +static NSDateFormatter *__rfc1123DateFormatter; @implementation RKRequestCache @synthesize storagePolicy = _storagePolicy; -+ (NSDateFormatter*)rfc1123DateFormatter { ++ (NSDateFormatter *)rfc1123DateFormatter +{ if (__rfc1123DateFormatter == nil) { __rfc1123DateFormatter = [[NSDateFormatter alloc] init]; [__rfc1123DateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; @@ -48,7 +49,8 @@ + (NSDateFormatter*)rfc1123DateFormatter { return __rfc1123DateFormatter; } -- (id)initWithPath:(NSString*)cachePath storagePolicy:(RKRequestCacheStoragePolicy)storagePolicy { +- (id)initWithPath:(NSString *)cachePath storagePolicy:(RKRequestCacheStoragePolicy)storagePolicy +{ self = [super init]; if (self) { _cache = [[RKCache alloc] initWithPath:cachePath @@ -61,19 +63,22 @@ - (id)initWithPath:(NSString*)cachePath storagePolicy:(RKRequestCacheStoragePoli return self; } -- (void)dealloc { +- (void)dealloc +{ [_cache release]; _cache = nil; [super dealloc]; } -- (NSString*)path { +- (NSString *)path +{ return _cache.cachePath; } -- (NSString*)pathForRequest:(RKRequest*)request { - NSString* pathForRequest = nil; - NSString* requestCacheKey = [request cacheKey]; +- (NSString *)pathForRequest:(RKRequest *)request +{ + NSString *pathForRequest = nil; + NSString *requestCacheKey = [request cacheKey]; if (requestCacheKey) { if (_storagePolicy == RKRequestCacheStoragePolicyForDurationOfSession) { pathForRequest = [RKRequestCacheSessionCacheDirectory stringByAppendingPathComponent:requestCacheKey]; @@ -88,9 +93,10 @@ - (NSString*)pathForRequest:(RKRequest*)request { return pathForRequest; } -- (BOOL)hasResponseForRequest:(RKRequest*)request { +- (BOOL)hasResponseForRequest:(RKRequest *)request +{ BOOL hasEntryForRequest = NO; - NSString* cacheKey = [self pathForRequest:request]; + NSString *cacheKey = [self pathForRequest:request]; if (cacheKey) { hasEntryForRequest = ([_cache hasEntry:cacheKey] && [_cache hasEntry:[cacheKey stringByAppendingPathExtension:RKRequestCacheHeadersExtension]]); @@ -99,20 +105,21 @@ - (BOOL)hasResponseForRequest:(RKRequest*)request { return hasEntryForRequest; } -- (void)storeResponse:(RKResponse*)response forRequest:(RKRequest*)request { +- (void)storeResponse:(RKResponse *)response forRequest:(RKRequest *)request +{ if ([self hasResponseForRequest:request]) { [self invalidateRequest:request]; } if (_storagePolicy != RKRequestCacheStoragePolicyDisabled) { - NSString* cacheKey = [self pathForRequest:request]; + NSString *cacheKey = [self pathForRequest:request]; if (cacheKey) { [_cache writeData:response.body withCacheKey:cacheKey]; - NSMutableDictionary* headers = [response.allHeaderFields mutableCopy]; + NSMutableDictionary *headers = [response.allHeaderFields mutableCopy]; if (headers) { // TODO: expose this? - NSHTTPURLResponse* urlResponse = [response valueForKey:@"_httpURLResponse"]; + NSHTTPURLResponse *urlResponse = [response valueForKey:@"_httpURLResponse"]; // Cache Loaded Time [headers setObject:[[RKRequestCache rfc1123DateFormatter] stringFromDate:[NSDate date]] forKey:RKRequestCacheDateHeaderKey]; @@ -133,23 +140,25 @@ - (void)storeResponse:(RKResponse*)response forRequest:(RKRequest*)request { } } -- (RKResponse*)responseForRequest:(RKRequest*)request { - RKResponse* response = nil; - NSString* cacheKey = [self pathForRequest:request]; +- (RKResponse *)responseForRequest:(RKRequest *)request +{ + RKResponse *response = nil; + NSString *cacheKey = [self pathForRequest:request]; if (cacheKey) { - NSData* responseData = [_cache dataForCacheKey:cacheKey]; - NSDictionary* responseHeaders = [_cache dictionaryForCacheKey:[cacheKey stringByAppendingPathExtension:RKRequestCacheHeadersExtension]]; + NSData *responseData = [_cache dataForCacheKey:cacheKey]; + NSDictionary *responseHeaders = [_cache dictionaryForCacheKey:[cacheKey stringByAppendingPathExtension:RKRequestCacheHeadersExtension]]; response = [[[RKResponse alloc] initWithRequest:request body:responseData headers:responseHeaders] autorelease]; } RKLogDebug(@"Found cached RKResponse '%@' for '%@'", response, request); return response; } -- (NSDictionary*)headersForRequest:(RKRequest*)request { - NSDictionary* headers = nil; - NSString* cacheKey = [self pathForRequest:request]; +- (NSDictionary *)headersForRequest:(RKRequest *)request +{ + NSDictionary *headers = nil; + NSString *cacheKey = [self pathForRequest:request]; if (cacheKey) { - NSString* headersCacheKey = [cacheKey stringByAppendingPathExtension:RKRequestCacheHeadersExtension]; + NSString *headersCacheKey = [cacheKey stringByAppendingPathExtension:RKRequestCacheHeadersExtension]; headers = [_cache dictionaryForCacheKey:headersCacheKey]; if (headers) { RKLogDebug(@"Read cached headers '%@' from headersCacheKey '%@' for '%@'", headers, headersCacheKey, request); @@ -162,12 +171,13 @@ - (NSDictionary*)headersForRequest:(RKRequest*)request { return headers; } -- (NSString*)etagForRequest:(RKRequest*)request { - NSString* etag = nil; +- (NSString *)etagForRequest:(RKRequest *)request +{ + NSString *etag = nil; - NSDictionary* responseHeaders = [self headersForRequest:request]; + NSDictionary *responseHeaders = [self headersForRequest:request]; if (responseHeaders) { - for (NSString* responseHeader in responseHeaders) { + for (NSString *responseHeader in responseHeaders) { if ([[responseHeader uppercaseString] isEqualToString:[@"ETag" uppercaseString]]) { etag = [responseHeaders objectForKey:responseHeader]; } @@ -177,10 +187,11 @@ - (NSString*)etagForRequest:(RKRequest*)request { return etag; } -- (void)setCacheDate:(NSDate*)date forRequest:(RKRequest*)request { - NSString* cacheKey = [self pathForRequest:request]; +- (void)setCacheDate:(NSDate *)date forRequest:(RKRequest *)request +{ + NSString *cacheKey = [self pathForRequest:request]; if (cacheKey) { - NSMutableDictionary* responseHeaders = [[self headersForRequest:request] mutableCopy]; + NSMutableDictionary *responseHeaders = [[self headersForRequest:request] mutableCopy]; [responseHeaders setObject:[[RKRequestCache rfc1123DateFormatter] stringFromDate:date] forKey:RKRequestCacheDateHeaderKey]; @@ -190,13 +201,14 @@ - (void)setCacheDate:(NSDate*)date forRequest:(RKRequest*)request { } } -- (NSDate*)cacheDateForRequest:(RKRequest*)request { - NSDate* date = nil; - NSString* dateString = nil; +- (NSDate *)cacheDateForRequest:(RKRequest *)request +{ + NSDate *date = nil; + NSString *dateString = nil; - NSDictionary* responseHeaders = [self headersForRequest:request]; + NSDictionary *responseHeaders = [self headersForRequest:request]; if (responseHeaders) { - for (NSString* responseHeader in responseHeaders) { + for (NSString *responseHeader in responseHeaders) { if ([[responseHeader uppercaseString] isEqualToString:[RKRequestCacheDateHeaderKey uppercaseString]]) { dateString = [responseHeaders objectForKey:responseHeader]; } @@ -207,9 +219,10 @@ - (NSDate*)cacheDateForRequest:(RKRequest*)request { return date; } -- (void)invalidateRequest:(RKRequest*)request { +- (void)invalidateRequest:(RKRequest *)request +{ RKLogDebug(@"Invalidating cache entry for '%@'", request); - NSString* cacheKey = [self pathForRequest:request]; + NSString *cacheKey = [self pathForRequest:request]; if (cacheKey) { [_cache invalidateEntry:cacheKey]; [_cache invalidateEntry:[cacheKey stringByAppendingPathExtension:RKRequestCacheHeadersExtension]]; @@ -217,7 +230,8 @@ - (void)invalidateRequest:(RKRequest*)request { } } -- (void)invalidateWithStoragePolicy:(RKRequestCacheStoragePolicy)storagePolicy { +- (void)invalidateWithStoragePolicy:(RKRequestCacheStoragePolicy)storagePolicy +{ if (storagePolicy != RKRequestCacheStoragePolicyDisabled) { if (storagePolicy == RKRequestCacheStoragePolicyForDurationOfSession) { [_cache invalidateSubDirectory:RKRequestCacheSessionCacheDirectory]; @@ -227,13 +241,15 @@ - (void)invalidateWithStoragePolicy:(RKRequestCacheStoragePolicy)storagePolicy { } } -- (void)invalidateAll { +- (void)invalidateAll +{ RKLogInfo(@"Invalidating all cache entries..."); [_cache invalidateSubDirectory:RKRequestCacheSessionCacheDirectory]; [_cache invalidateSubDirectory:RKRequestCachePermanentCacheDirectory]; } -- (void)setStoragePolicy:(RKRequestCacheStoragePolicy)storagePolicy { +- (void)setStoragePolicy:(RKRequestCacheStoragePolicy)storagePolicy +{ [self invalidateWithStoragePolicy:RKRequestCacheStoragePolicyForDurationOfSession]; if (storagePolicy == RKRequestCacheStoragePolicyDisabled) { [self invalidateWithStoragePolicy:RKRequestCacheStoragePolicyPermanently]; diff --git a/Code/Network/RKRequestQueue.h b/Code/Network/RKRequestQueue.h index f7308f0690..7ec1244f43 100644 --- a/Code/Network/RKRequestQueue.h +++ b/Code/Network/RKRequestQueue.h @@ -28,14 +28,9 @@ RKRequest objects. */ @interface RKRequestQueue : NSObject { - NSString *_name; NSMutableArray *_requests; NSMutableSet *_loadingRequests; - NSObject *_delegate; - NSUInteger _concurrentRequestsLimit; - NSUInteger _requestTimeout; NSTimer *_queueTimer; - BOOL _suspended; BOOL _showsNetworkActivityIndicatorWhenBusy; } diff --git a/Code/Network/RKRequestQueue.m b/Code/Network/RKRequestQueue.m index 88eb637360..e227389ccd 100644 --- a/Code/Network/RKRequestQueue.m +++ b/Code/Network/RKRequestQueue.m @@ -32,7 +32,7 @@ RK_FIX_CATEGORY_BUG(UIApplication_RKNetworkActivity) // Constants -static NSMutableArray* RKRequestQueueInstances = nil; +static NSMutableArray *RKRequestQueueInstances = nil; static const NSTimeInterval kFlushDelay = 0.3; @@ -41,7 +41,7 @@ #define RKLogComponent lcl_cRestKitNetworkQueue @interface RKRequestQueue () -@property (nonatomic, retain, readwrite) NSString* name; +@property (nonatomic, retain, readwrite) NSString *name; @end @implementation RKRequestQueue @@ -56,21 +56,25 @@ @implementation RKRequestQueue @synthesize showsNetworkActivityIndicatorWhenBusy = _showsNetworkActivityIndicatorWhenBusy; #endif -+ (RKRequestQueue*)sharedQueue { ++ (RKRequestQueue *)sharedQueue +{ RKLogWarning(@"Deprecated invocation of [RKRequestQueue sharedQueue]. Returning [RKClient sharedClient].requestQueue. Update your code to reference the queue you want explicitly."); return [RKClient sharedClient].requestQueue; } -+ (void)setSharedQueue:(RKRequestQueue*)requestQueue { ++ (void)setSharedQueue:(RKRequestQueue *)requestQueue +{ RKLogWarning(@"Deprecated access to [RKRequestQueue setSharedQueue:]. Invoking [[RKClient sharedClient] setRequestQueue:]. Update your code to reference the specific queue instance you want."); [RKClient sharedClient].requestQueue = requestQueue; } -+ (id)requestQueue { ++ (id)requestQueue +{ return [[self new] autorelease]; } -+ (id)newRequestQueueWithName:(NSString*)name { ++ (id)newRequestQueueWithName:(NSString *)name +{ if (RKRequestQueueInstances == nil) { RKRequestQueueInstances = [NSMutableArray new]; } @@ -79,14 +83,15 @@ + (id)newRequestQueueWithName:(NSString*)name { return nil; } - RKRequestQueue* queue = [self new]; + RKRequestQueue *queue = [self new]; queue.name = name; [RKRequestQueueInstances addObject:[NSValue valueWithNonretainedObject:queue]]; return queue; } -+ (id)requestQueueWithName:(NSString *)name { ++ (id)requestQueueWithName:(NSString *)name +{ if (RKRequestQueueInstances == nil) { RKRequestQueueInstances = [NSMutableArray new]; } @@ -94,8 +99,8 @@ + (id)requestQueueWithName:(NSString *)name { // Find existing reference NSArray *requestQueueInstances = [RKRequestQueueInstances copy]; RKRequestQueue *namedQueue = nil; - for (NSValue* value in requestQueueInstances) { - RKRequestQueue* queue = (RKRequestQueue*) [value nonretainedObjectValue]; + for (NSValue *value in requestQueueInstances) { + RKRequestQueue *queue = (RKRequestQueue *)[value nonretainedObjectValue]; if ([queue.name isEqualToString:name]) { namedQueue = queue; break; @@ -112,12 +117,13 @@ + (id)requestQueueWithName:(NSString *)name { return namedQueue; } -+ (BOOL)requestQueueExistsWithName:(NSString*)name { ++ (BOOL)requestQueueExistsWithName:(NSString *)name +{ BOOL queueExists = NO; if (RKRequestQueueInstances) { NSArray *requestQueueInstances = [RKRequestQueueInstances copy]; - for (NSValue* value in requestQueueInstances) { - RKRequestQueue* queue = (RKRequestQueue*) [value nonretainedObjectValue]; + for (NSValue *value in requestQueueInstances) { + RKRequestQueue *queue = (RKRequestQueue *)[value nonretainedObjectValue]; if ([queue.name isEqualToString:name]) { queueExists = YES; break; @@ -129,7 +135,8 @@ + (BOOL)requestQueueExistsWithName:(NSString*)name { return queueExists; } -- (id)init { +- (id)init +{ if ((self = [super init])) { _requests = [[NSMutableArray alloc] init]; _loadingRequests = [[NSMutableSet alloc] init]; @@ -155,10 +162,11 @@ - (id)init { return self; } -- (void)removeFromNamedQueues { +- (void)removeFromNamedQueues +{ if (self.name) { - for (NSValue* value in RKRequestQueueInstances) { - RKRequestQueue* queue = (RKRequestQueue*) [value nonretainedObjectValue]; + for (NSValue *value in RKRequestQueueInstances) { + RKRequestQueue *queue = (RKRequestQueue *)[value nonretainedObjectValue]; if ([queue.name isEqualToString:self.name]) { [RKRequestQueueInstances removeObject:value]; return; @@ -167,7 +175,8 @@ - (void)removeFromNamedQueues { } } -- (void)dealloc { +- (void)dealloc +{ RKLogDebug(@"Queue instance is being deallocated: %@", self); [[NSNotificationCenter defaultCenter] removeObserver:self]; @@ -182,21 +191,25 @@ - (void)dealloc { [super dealloc]; } -- (NSUInteger)count { +- (NSUInteger)count +{ return [_requests count]; } -- (NSString*)description { +- (NSString *)description +{ return [NSString stringWithFormat:@"<%@: %p name=%@ suspended=%@ requestCount=%d loadingCount=%d/%d>", NSStringFromClass([self class]), self, self.name, self.suspended ? @"YES" : @"NO", self.count, self.loadingCount, self.concurrentRequestsLimit]; } -- (NSUInteger)loadingCount { +- (NSUInteger)loadingCount +{ return [_loadingRequests count]; } -- (void)addLoadingRequest:(RKRequest*)request { +- (void)addLoadingRequest:(RKRequest *)request +{ if (self.loadingCount == 0) { RKLogTrace(@"Loading count increasing from 0 to 1. Firing requestQueueDidBeginLoading"); @@ -214,10 +227,11 @@ - (void)addLoadingRequest:(RKRequest*)request { @synchronized(self) { [_loadingRequests addObject:request]; } - RKLogTrace(@"Loading count now %ld for queue %@", (long) self.loadingCount, self); + RKLogTrace(@"Loading count now %ld for queue %@", (long)self.loadingCount, self); } -- (void)removeLoadingRequest:(RKRequest*)request { +- (void)removeLoadingRequest:(RKRequest *)request +{ if (self.loadingCount == 1 && [_loadingRequests containsObject:request]) { RKLogTrace(@"Loading count decreasing from 1 to 0. Firing requestQueueDidFinishLoading"); @@ -235,10 +249,11 @@ - (void)removeLoadingRequest:(RKRequest*)request { @synchronized(self) { [_loadingRequests removeObject:request]; } - RKLogTrace(@"Loading count now %ld for queue %@", (long) self.loadingCount, self); + RKLogTrace(@"Loading count now %ld for queue %@", (long)self.loadingCount, self); } -- (void)loadNextInQueueDelayed { +- (void)loadNextInQueueDelayed +{ if (!_queueTimer) { _queueTimer = [NSTimer scheduledTimerWithTimeInterval:kFlushDelay target:self @@ -249,9 +264,10 @@ - (void)loadNextInQueueDelayed { } } -- (RKRequest*)nextRequest { +- (RKRequest *)nextRequest +{ for (NSUInteger i = 0; i < [_requests count]; i++) { - RKRequest* request = [_requests objectAtIndex:i]; + RKRequest *request = [_requests objectAtIndex:i]; if ([request isUnsent]) { return request; } @@ -260,7 +276,8 @@ - (RKRequest*)nextRequest { return nil; } -- (void)loadNextInQueue { +- (void)loadNextInQueue +{ // We always want to dispatch requests from the main thread so the current thread does not terminate // and cause us to lose the delegate callbacks if (! [NSThread isMainThread]) { @@ -277,11 +294,11 @@ - (void)loadNextInQueue { return; } - NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; _queueTimer = nil; @synchronized(self) { - RKRequest* request = [self nextRequest]; + RKRequest *request = [self nextRequest]; while (request && self.loadingCount < _concurrentRequestsLimit) { RKLogTrace(@"Processing request %@ in queue %@", request, self); if ([_delegate respondsToSelector:@selector(requestQueue:willSendRequest:)]) { @@ -289,7 +306,7 @@ - (void)loadNextInQueue { } [self addLoadingRequest:request]; - RKLogDebug(@"Sent request %@ from queue %@. Loading count = %ld of %ld", request, self, (long) self.loadingCount, (long) _concurrentRequestsLimit); + RKLogDebug(@"Sent request %@ from queue %@. Loading count = %ld of %ld", request, self, (long)self.loadingCount, (long)_concurrentRequestsLimit); [request sendAsynchronously]; if ([_delegate respondsToSelector:@selector(requestQueue:didSendRequest:)]) { @@ -307,7 +324,8 @@ - (void)loadNextInQueue { [pool drain]; } -- (void)setSuspended:(BOOL)isSuspended { +- (void)setSuspended:(BOOL)isSuspended +{ if (_suspended != isSuspended) { if (isSuspended) { RKLogDebug(@"Queue %@ has been suspended", self); @@ -336,7 +354,8 @@ - (void)setSuspended:(BOOL)isSuspended { } } -- (void)addRequest:(RKRequest*)request { +- (void)addRequest:(RKRequest *)request +{ RKLogTrace(@"Request %@ added to queue %@", request, self); NSAssert(![self containsRequest:request], @"Attempting to add the same request multiple times"); @@ -361,7 +380,8 @@ - (void)addRequest:(RKRequest*)request { [self loadNextInQueue]; } -- (BOOL)removeRequest:(RKRequest*)request { +- (BOOL)removeRequest:(RKRequest *)request +{ if ([self containsRequest:request]) { RKLogTrace(@"Removing request %@ from queue %@", request, self); @synchronized(self) { @@ -381,13 +401,15 @@ - (BOOL)removeRequest:(RKRequest*)request { return NO; } -- (BOOL)containsRequest:(RKRequest*)request { +- (BOOL)containsRequest:(RKRequest *)request +{ @synchronized(self) { return [_requests containsObject:request]; } } -- (void)cancelRequest:(RKRequest*)request loadNext:(BOOL)loadNext { +- (void)cancelRequest:(RKRequest *)request loadNext:(BOOL)loadNext +{ if ([request isUnsent]) { RKLogDebug(@"Cancelled undispatched request %@ and removed from queue %@", request, self); @@ -415,16 +437,18 @@ - (void)cancelRequest:(RKRequest*)request loadNext:(BOOL)loadNext { } } -- (void)cancelRequest:(RKRequest*)request { +- (void)cancelRequest:(RKRequest *)request +{ [self cancelRequest:request loadNext:YES]; } -- (void)cancelRequestsWithDelegate:(NSObject*)delegate { +- (void)cancelRequestsWithDelegate:(NSObject *)delegate +{ RKLogDebug(@"Cancelling all request in queue %@ with delegate %p", self, delegate); - NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; - NSArray* requestsCopy = [NSArray arrayWithArray:_requests]; - for (RKRequest* request in requestsCopy) { + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + NSArray *requestsCopy = [NSArray arrayWithArray:_requests]; + for (RKRequest *request in requestsCopy) { if (request.delegate && request.delegate == delegate) { [self cancelRequest:request]; } @@ -432,12 +456,13 @@ - (void)cancelRequestsWithDelegate:(NSObject*)delegate { [pool drain]; } -- (void)abortRequestsWithDelegate:(NSObject*)delegate { +- (void)abortRequestsWithDelegate:(NSObject *)delegate +{ RKLogDebug(@"Aborting all request in queue %@ with delegate %p", self, delegate); - NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; - NSArray* requestsCopy = [NSArray arrayWithArray:_requests]; - for (RKRequest* request in requestsCopy) { + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + NSArray *requestsCopy = [NSArray arrayWithArray:_requests]; + for (RKRequest *request in requestsCopy) { if (request.delegate && request.delegate == delegate) { request.delegate = nil; [self cancelRequest:request]; @@ -446,33 +471,36 @@ - (void)abortRequestsWithDelegate:(NSObject*)delegate { [pool drain]; } -- (void)cancelAllRequests { +- (void)cancelAllRequests +{ RKLogDebug(@"Cancelling all request in queue %@", self); - NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; - NSArray* requestsCopy = [NSArray arrayWithArray:_requests]; - for (RKRequest* request in requestsCopy) { + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + NSArray *requestsCopy = [NSArray arrayWithArray:_requests]; + for (RKRequest *request in requestsCopy) { [self cancelRequest:request loadNext:NO]; } [pool drain]; } -- (void)start { +- (void)start +{ RKLogDebug(@"Started queue %@", self); [self setSuspended:NO]; } -- (void)processRequestDidLoadResponseNotification:(NSNotification *)notification { +- (void)processRequestDidLoadResponseNotification:(NSNotification *)notification +{ NSAssert([notification.object isKindOfClass:[RKRequest class]], @"Notification expected to contain an RKRequest, got a %@", NSStringFromClass([notification.object class])); RKLogTrace(@"Received notification: %@", notification); - RKRequest* request = (RKRequest*)notification.object; - NSDictionary* userInfo = [notification userInfo]; + RKRequest *request = (RKRequest *)notification.object; + NSDictionary *userInfo = [notification userInfo]; // We successfully loaded a response - RKLogDebug(@"Received response for request %@, removing from queue. (Now loading %ld of %ld)", request, (long) self.loadingCount, (long) _concurrentRequestsLimit); + RKLogDebug(@"Received response for request %@, removing from queue. (Now loading %ld of %ld)", request, (long)self.loadingCount, (long)_concurrentRequestsLimit); - RKResponse* response = [userInfo objectForKey:RKRequestDidLoadResponseNotificationUserInfoResponseKey]; + RKResponse *response = [userInfo objectForKey:RKRequestDidLoadResponseNotificationUserInfoResponseKey]; if ([_delegate respondsToSelector:@selector(requestQueue:didLoadResponse:)]) { [_delegate requestQueue:self didLoadResponse:response]; } @@ -481,19 +509,20 @@ - (void)processRequestDidLoadResponseNotification:(NSNotification *)notification [self loadNextInQueue]; } -- (void)processRequestDidFailWithErrorNotification:(NSNotification *)notification { +- (void)processRequestDidFailWithErrorNotification:(NSNotification *)notification +{ NSAssert([notification.object isKindOfClass:[RKRequest class]], @"Notification expected to contain an RKRequest, got a %@", NSStringFromClass([notification.object class])); RKLogTrace(@"Received notification: %@", notification); - RKRequest* request = (RKRequest*)notification.object; - NSDictionary* userInfo = [notification userInfo]; + RKRequest *request = (RKRequest *)notification.object; + NSDictionary *userInfo = [notification userInfo]; // We failed with an error - NSError* error = nil; + NSError *error = nil; if (userInfo) { error = [userInfo objectForKey:RKRequestDidFailWithErrorNotificationUserInfoErrorKey]; RKLogDebug(@"Request %@ failed loading in queue %@ with error: %@.(Now loading %ld of %ld)", request, self, - [error localizedDescription], (long) self.loadingCount, (long) _concurrentRequestsLimit); + [error localizedDescription], (long)self.loadingCount, (long)_concurrentRequestsLimit); } else { RKLogWarning(@"Received RKRequestDidFailWithErrorNotification without a userInfo, something is amiss..."); } @@ -510,11 +539,12 @@ - (void)processRequestDidFailWithErrorNotification:(NSNotification *)notificatio Invoked via observation when a request has loaded a response or failed with an error. Remove the completed request from the queue and continue processing */ -- (void)processRequestDidFinishLoadingNotification:(NSNotification *)notification { +- (void)processRequestDidFinishLoadingNotification:(NSNotification *)notification +{ NSAssert([notification.object isKindOfClass:[RKRequest class]], @"Notification expected to contain an RKRequest, got a %@", NSStringFromClass([notification.object class])); RKLogTrace(@"Received notification: %@", notification); - RKRequest* request = (RKRequest*)notification.object; + RKRequest *request = (RKRequest *)notification.object; if ([self containsRequest:request]) { [self removeRequest:request]; @@ -527,14 +557,16 @@ - (void)processRequestDidFinishLoadingNotification:(NSNotification *)notificatio #pragma mark - Background Request Support -- (void)willTransitionToBackground { +- (void)willTransitionToBackground +{ RKLogDebug(@"App is transitioning into background, suspending queue"); // Suspend the queue so background requests do not trigger additional requests on state changes self.suspended = YES; } -- (void)willTransitionToForeground { +- (void)willTransitionToForeground +{ RKLogDebug(@"App returned from background, unsuspending queue"); self.suspended = NO; @@ -548,14 +580,16 @@ @implementation UIApplication (RKNetworkActivity) static NSInteger networkActivityCount; -- (NSInteger)networkActivityCount { +- (NSInteger)networkActivityCount +{ @synchronized(self) { return networkActivityCount; } } -- (void)refreshActivityIndicator { - if(![NSThread isMainThread]) { +- (void)refreshActivityIndicator +{ + if (![NSThread isMainThread]) { SEL sel_refresh = @selector(refreshActivityIndicator); [self performSelectorOnMainThread:sel_refresh withObject:nil waitUntilDone:NO]; return; @@ -564,14 +598,16 @@ - (void)refreshActivityIndicator { self.networkActivityIndicatorVisible = active; } -- (void)pushNetworkActivity { +- (void)pushNetworkActivity +{ @synchronized(self) { networkActivityCount++; } [self refreshActivityIndicator]; } -- (void)popNetworkActivity { +- (void)popNetworkActivity +{ @synchronized(self) { if (networkActivityCount > 0) { networkActivityCount--; @@ -583,7 +619,8 @@ - (void)popNetworkActivity { [self refreshActivityIndicator]; } -- (void)resetNetworkActivity { +- (void)resetNetworkActivity +{ @synchronized(self) { networkActivityCount = 0; } diff --git a/Code/Network/RKRequestSerialization.h b/Code/Network/RKRequestSerialization.h index 62317f28b3..b78b3a17cd 100644 --- a/Code/Network/RKRequestSerialization.h +++ b/Code/Network/RKRequestSerialization.h @@ -27,10 +27,7 @@ @see RKRequestSerializable */ -@interface RKRequestSerialization : NSObject { - NSData *_data; - NSString *_MIMEType; -} +@interface RKRequestSerialization : NSObject ///----------------------------------------------------------------------------- diff --git a/Code/Network/RKRequestSerialization.m b/Code/Network/RKRequestSerialization.m index f00c12d2ee..db800f6262 100644 --- a/Code/Network/RKRequestSerialization.m +++ b/Code/Network/RKRequestSerialization.m @@ -25,7 +25,8 @@ @implementation RKRequestSerialization @synthesize data = _data; @synthesize MIMEType = _MIMEType; -- (id)initWithData:(NSData *)data MIMEType:(NSString *)MIMEType { +- (id)initWithData:(NSData *)data MIMEType:(NSString *)MIMEType +{ NSAssert(data, @"Cannot create a request serialization without Data"); NSAssert(MIMEType, @"Cannot create a request serialization without a MIME Type"); @@ -38,26 +39,31 @@ - (id)initWithData:(NSData *)data MIMEType:(NSString *)MIMEType { return self; } -+ (id)serializationWithData:(NSData *)data MIMEType:(NSString *)MIMEType { ++ (id)serializationWithData:(NSData *)data MIMEType:(NSString *)MIMEType +{ return [[[RKRequestSerialization alloc] initWithData:data MIMEType:MIMEType] autorelease]; } -- (void)dealloc { +- (void)dealloc +{ [_data release]; [_MIMEType release]; [super dealloc]; } -- (NSString *)HTTPHeaderValueForContentType { +- (NSString *)HTTPHeaderValueForContentType +{ return self.MIMEType; } -- (NSData *)HTTPBody { +- (NSData *)HTTPBody +{ return self.data; } -- (NSUInteger)HTTPHeaderValueForContentLength { +- (NSUInteger)HTTPHeaderValueForContentLength +{ return [self.data length]; } diff --git a/Code/Network/RKRequest_Internals.h b/Code/Network/RKRequest_Internals.h index 1184188d55..a9bdeb07f3 100644 --- a/Code/Network/RKRequest_Internals.h +++ b/Code/Network/RKRequest_Internals.h @@ -20,6 +20,6 @@ @interface RKRequest (Internals) - (BOOL)prepareURLRequest; -- (void)didFailLoadWithError:(NSError*)error; +- (void)didFailLoadWithError:(NSError *)error; - (void)finalizeLoad:(BOOL)successful; @end diff --git a/Code/Network/RKResponse.h b/Code/Network/RKResponse.h index 2ce426f39a..2a64774a3d 100644 --- a/Code/Network/RKResponse.h +++ b/Code/Network/RKResponse.h @@ -25,10 +25,8 @@ Models the response portion of an HTTP request/response cycle */ @interface RKResponse : NSObject { - RKRequest *_request; NSHTTPURLResponse *_httpURLResponse; NSMutableData *_body; - NSError *_failureError; BOOL _loading; NSDictionary *_responseHeaders; } diff --git a/Code/Network/RKResponse.m b/Code/Network/RKResponse.m index 5a1bde7a22..d2aa268208 100644 --- a/Code/Network/RKResponse.m +++ b/Code/Network/RKResponse.m @@ -40,7 +40,8 @@ @implementation RKResponse @synthesize request = _request; @synthesize failureError = _failureError; -- (id)init { +- (id)init +{ self = [super init]; if (self) { _body = [[NSMutableData alloc] init]; @@ -52,7 +53,8 @@ - (id)init { return self; } -- (id)initWithRequest:(RKRequest *)request { +- (id)initWithRequest:(RKRequest *)request +{ self = [self init]; if (self) { // We don't retain here as we're letting RKRequestQueue manage @@ -63,7 +65,8 @@ - (id)initWithRequest:(RKRequest *)request { return self; } -- (id)initWithRequest:(RKRequest*)request body:(NSData*)body headers:(NSDictionary*)headers { +- (id)initWithRequest:(RKRequest *)request body:(NSData *)body headers:(NSDictionary *)headers +{ self = [self initWithRequest:request]; if (self) { [_body release]; @@ -74,7 +77,8 @@ - (id)initWithRequest:(RKRequest*)request body:(NSData*)body headers:(NSDictiona return self; } -- (id)initWithSynchronousRequest:(RKRequest*)request URLResponse:(NSHTTPURLResponse*)URLResponse body:(NSData*)body error:(NSError*)error { +- (id)initWithSynchronousRequest:(RKRequest *)request URLResponse:(NSHTTPURLResponse *)URLResponse body:(NSData *)body error:(NSError *)error +{ self = [super init]; if (self) { _request = request; @@ -87,7 +91,8 @@ - (id)initWithSynchronousRequest:(RKRequest*)request URLResponse:(NSHTTPURLRespo return self; } -- (void)dealloc { +- (void)dealloc +{ _request = nil; [_httpURLResponse release]; _httpURLResponse = nil; @@ -100,16 +105,18 @@ - (void)dealloc { [super dealloc]; } -- (BOOL)hasCredentials { +- (BOOL)hasCredentials +{ return _request.username && _request.password; } -- (BOOL)isServerTrusted:(SecTrustRef)trust { +- (BOOL)isServerTrusted:(SecTrustRef)trust +{ BOOL proceed = NO; if (_request.disableCertificateValidation) { proceed = YES; - } else if ([_request.additionalRootCertificates count] > 0 ) { + } else if ([_request.additionalRootCertificates count] > 0) { CFArrayRef rootCerts = (CFArrayRef)[_request.additionalRootCertificates allObjects]; SecTrustResultType result; OSStatus returnCode; @@ -134,7 +141,8 @@ - (BOOL)isServerTrusted:(SecTrustRef)trust { } // Handle basic auth & SSL certificate validation -- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge { +- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge +{ RKResponseIgnoreDelegateIfCancelled(); RKLogDebug(@"Received authentication challenge"); @@ -150,18 +158,19 @@ - (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallen if ([challenge previousFailureCount] == 0) { NSURLCredential *newCredential; - newCredential=[NSURLCredential credentialWithUser:[NSString stringWithFormat:@"%@", _request.username] - password:[NSString stringWithFormat:@"%@", _request.password] - persistence:NSURLCredentialPersistenceNone]; + newCredential = [NSURLCredential credentialWithUser:[NSString stringWithFormat:@"%@", _request.username] + password:[NSString stringWithFormat:@"%@", _request.password] + persistence:NSURLCredentialPersistenceNone]; [[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge]; } else { - RKLogWarning(@"Failed authentication challenge after %ld failures", (long) [challenge previousFailureCount]); + RKLogWarning(@"Failed authentication challenge after %ld failures", (long)[challenge previousFailureCount]); [[challenge sender] cancelAuthenticationChallenge:challenge]; } } -- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)space { +- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)space +{ RKResponseIgnoreDelegateIfCancelled(NO); RKLogDebug(@"Asked if canAuthenticateAgainstProtectionSpace: with authenticationMethod = %@", [space authenticationMethod]); if ([[space authenticationMethod] isEqualToString:NSURLAuthenticationMethodServerTrust]) { @@ -183,7 +192,8 @@ - (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectio return hasCredentials; } -- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response { +- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response +{ if (nil == response || _request.followRedirect) { RKLogDebug(@"Proceeding with request to %@", request); return request; @@ -193,7 +203,8 @@ - (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSUR } } -- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { +- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data +{ RKResponseIgnoreDelegateIfCancelled(); [_body appendData:data]; [_request invalidateTimeoutTimer]; @@ -202,9 +213,10 @@ - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { } } -- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response { +- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response +{ RKResponseIgnoreDelegateIfCancelled(); - RKLogDebug(@"NSHTTPURLResponse Status Code: %ld", (long) [response statusCode]); + RKLogDebug(@"NSHTTPURLResponse Status Code: %ld", (long)[response statusCode]); RKLogDebug(@"Headers: %@", [response allHeaderFields]); _httpURLResponse = [response retain]; [_request invalidateTimeoutTimer]; @@ -213,20 +225,23 @@ - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLRe } } -- (void)connectionDidFinishLoading:(NSURLConnection *)connection { +- (void)connectionDidFinishLoading:(NSURLConnection *)connection +{ RKResponseIgnoreDelegateIfCancelled(); RKLogTrace(@"Read response body: %@", [self bodyAsString]); [_request didFinishLoad:self]; } -- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { +- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error +{ RKResponseIgnoreDelegateIfCancelled(); _failureError = [error retain]; [_request invalidateTimeoutTimer]; [_request didFailLoadWithError:_failureError]; } -- (NSInputStream *)connection:(NSURLConnection *)connection needNewBodyStream:(NSURLRequest *)request { +- (NSInputStream *)connection:(NSURLConnection *)connection needNewBodyStream:(NSURLRequest *)request +{ RKResponseIgnoreDelegateIfCancelled(nil); RKLogWarning(@"RestKit was asked to retransmit a new body stream for a request. Possible connection error or authentication challenge?"); return nil; @@ -238,7 +253,8 @@ - (NSInputStream *)connection:(NSURLConnection *)connection needNewBodyStream:(N // Therefore, we ensure the delegate recieves the did start loading here and // in connection:didReceiveResponse: to ensure that the RKRequestDelegate // callbacks get called in the correct order. -- (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite { +- (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite +{ RKResponseIgnoreDelegateIfCancelled(); [_request invalidateTimeoutTimer]; @@ -247,37 +263,44 @@ - (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)byte } } -- (NSString*)localizedStatusCodeString { +- (NSString *)localizedStatusCodeString +{ return [NSHTTPURLResponse localizedStringForStatusCode:[self statusCode]]; } -- (NSData *)body { +- (NSData *)body +{ return _body; } -- (NSString *)bodyEncodingName { +- (NSString *)bodyEncodingName +{ return [_httpURLResponse textEncodingName]; } -- (NSStringEncoding)bodyEncoding { +- (NSStringEncoding)bodyEncoding +{ CFStringEncoding cfEncoding = kCFStringEncodingInvalidId; NSString *textEncodingName = [self bodyEncodingName]; if (textEncodingName) { - cfEncoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef) textEncodingName); + cfEncoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)textEncodingName); } return (cfEncoding == kCFStringEncodingInvalidId) ? self.request.defaultHTTPEncoding : CFStringConvertEncodingToNSStringEncoding(cfEncoding); } -- (NSString *)bodyAsString { +- (NSString *)bodyAsString +{ return [[[NSString alloc] initWithData:self.body encoding:[self bodyEncoding]] autorelease]; } -- (id)bodyAsJSON { +- (id)bodyAsJSON +{ [NSException raise:nil format:@"Reimplemented as parsedBody"]; return nil; } -- (id)parsedBody:(NSError**)error { +- (id)parsedBody:(NSError **)error +{ id parser = [[RKParserRegistry sharedRegistry] parserForMIMEType:[self MIMEType]]; if (! parser) { RKLogWarning(@"Unable to parse response body: no parser registered for MIME Type '%@'", [self MIMEType]); @@ -293,7 +316,8 @@ - (id)parsedBody:(NSError**)error { return object; } -- (NSString*)failureErrorDescription { +- (NSString *)failureErrorDescription +{ if ([self isFailure]) { return [_failureError localizedDescription]; } else { @@ -301,161 +325,195 @@ - (NSString*)failureErrorDescription { } } -- (BOOL)wasLoadedFromCache { +- (BOOL)wasLoadedFromCache +{ return (_responseHeaders != nil); } -- (NSURL*)URL { +- (NSURL *)URL +{ if ([self wasLoadedFromCache]) { return [NSURL URLWithString:[_responseHeaders valueForKey:RKRequestCacheURLHeadersKey]]; } return [_httpURLResponse URL]; } -- (NSString*)MIMEType { +- (NSString *)MIMEType +{ if ([self wasLoadedFromCache]) { return [_responseHeaders valueForKey:RKRequestCacheMIMETypeHeadersKey]; } return [_httpURLResponse MIMEType]; } -- (NSInteger)statusCode { +- (NSInteger)statusCode +{ if ([self wasLoadedFromCache]) { return [[_responseHeaders valueForKey:RKRequestCacheStatusCodeHeadersKey] intValue]; } return ([_httpURLResponse respondsToSelector:@selector(statusCode)] ? [_httpURLResponse statusCode] : 200); } -- (NSDictionary*)allHeaderFields { +- (NSDictionary *)allHeaderFields +{ if ([self wasLoadedFromCache]) { return _responseHeaders; } return ([_httpURLResponse respondsToSelector:@selector(allHeaderFields)] ? [_httpURLResponse allHeaderFields] : nil); } -- (NSArray*)cookies { +- (NSArray *)cookies +{ return [NSHTTPCookie cookiesWithResponseHeaderFields:self.allHeaderFields forURL:self.URL]; } -- (BOOL)isFailure { +- (BOOL)isFailure +{ return (nil != _failureError); } -- (BOOL)isInvalid { +- (BOOL)isInvalid +{ return ([self statusCode] < 100 || [self statusCode] > 600); } -- (BOOL)isInformational { +- (BOOL)isInformational +{ return ([self statusCode] >= 100 && [self statusCode] < 200); } -- (BOOL)isSuccessful { +- (BOOL)isSuccessful +{ return (([self statusCode] >= 200 && [self statusCode] < 300) || ([self wasLoadedFromCache])); } -- (BOOL)isRedirection { +- (BOOL)isRedirection +{ return ([self statusCode] >= 300 && [self statusCode] < 400); } -- (BOOL)isClientError { +- (BOOL)isClientError +{ return ([self statusCode] >= 400 && [self statusCode] < 500); } -- (BOOL)isServerError { +- (BOOL)isServerError +{ return ([self statusCode] >= 500 && [self statusCode] < 600); } -- (BOOL)isError { +- (BOOL)isError +{ return ([self isClientError] || [self isServerError]); } -- (BOOL)isOK { +- (BOOL)isOK +{ return ([self statusCode] == 200); } -- (BOOL)isCreated { +- (BOOL)isCreated +{ return ([self statusCode] == 201); } -- (BOOL)isNoContent { +- (BOOL)isNoContent +{ return ([self statusCode] == 204); } -- (BOOL)isNotModified { +- (BOOL)isNotModified +{ return ([self statusCode] == 304); } -- (BOOL)isUnauthorized { +- (BOOL)isUnauthorized +{ return ([self statusCode] == 401); } -- (BOOL)isForbidden { +- (BOOL)isForbidden +{ return ([self statusCode] == 403); } -- (BOOL)isNotFound { +- (BOOL)isNotFound +{ return ([self statusCode] == 404); } -- (BOOL)isConflict { +- (BOOL)isConflict +{ return ([self statusCode] == 409); } -- (BOOL)isGone { +- (BOOL)isGone +{ return ([self statusCode] == 410); } -- (BOOL)isUnprocessableEntity { +- (BOOL)isUnprocessableEntity +{ return ([self statusCode] == 422); } -- (BOOL)isRedirect { +- (BOOL)isRedirect +{ return ([self statusCode] == 301 || [self statusCode] == 302 || [self statusCode] == 303 || [self statusCode] == 307); } -- (BOOL)isEmpty { +- (BOOL)isEmpty +{ return ([self statusCode] == 201 || [self statusCode] == 204 || [self statusCode] == 304); } -- (BOOL)isServiceUnavailable { +- (BOOL)isServiceUnavailable +{ return ([self statusCode] == 503); } -- (NSString*)contentType { +- (NSString *)contentType +{ return ([[self allHeaderFields] objectForKey:@"Content-Type"]); } -- (NSString*)contentLength { +- (NSString *)contentLength +{ return ([[self allHeaderFields] objectForKey:@"Content-Length"]); } -- (NSString*)location { +- (NSString *)location +{ return ([[self allHeaderFields] objectForKey:@"Location"]); } -- (BOOL)isHTML { - NSString* contentType = [self contentType]; +- (BOOL)isHTML +{ + NSString *contentType = [self contentType]; return (contentType && ([contentType rangeOfString:@"text/html" options:NSCaseInsensitiveSearch|NSAnchoredSearch].length > 0 || [self isXHTML])); } -- (BOOL)isXHTML { - NSString* contentType = [self contentType]; +- (BOOL)isXHTML +{ + NSString *contentType = [self contentType]; return (contentType && [contentType rangeOfString:@"application/xhtml+xml" options:NSCaseInsensitiveSearch|NSAnchoredSearch].length > 0); } -- (BOOL)isXML { - NSString* contentType = [self contentType]; +- (BOOL)isXML +{ + NSString *contentType = [self contentType]; return (contentType && [contentType rangeOfString:@"application/xml" options:NSCaseInsensitiveSearch|NSAnchoredSearch].length > 0); } -- (BOOL)isJSON { - NSString* contentType = [self contentType]; +- (BOOL)isJSON +{ + NSString *contentType = [self contentType]; return (contentType && [contentType rangeOfString:@"application/json" options:NSCaseInsensitiveSearch|NSAnchoredSearch].length > 0); diff --git a/Code/Network/RKURL.m b/Code/Network/RKURL.m index bcced9c11c..0540928b50 100644 --- a/Code/Network/RKURL.m +++ b/Code/Network/RKURL.m @@ -35,33 +35,40 @@ @implementation RKURL @synthesize baseURL; @synthesize resourcePath; -+ (id)URLWithBaseURL:(NSURL *)baseURL { ++ (id)URLWithBaseURL:(NSURL *)baseURL +{ return [self URLWithBaseURL:baseURL resourcePath:nil queryParameters:nil]; } -+ (id)URLWithBaseURL:(NSURL *)baseURL resourcePath:(NSString *)resourcePath { ++ (id)URLWithBaseURL:(NSURL *)baseURL resourcePath:(NSString *)resourcePath +{ return [self URLWithBaseURL:baseURL resourcePath:resourcePath queryParameters:nil]; } -+ (id)URLWithBaseURL:(NSURL *)baseURL resourcePath:(NSString *)resourcePath queryParameters:(NSDictionary *)queryParameters { ++ (id)URLWithBaseURL:(NSURL *)baseURL resourcePath:(NSString *)resourcePath queryParameters:(NSDictionary *)queryParameters +{ return [[[self alloc] initWithBaseURL:baseURL resourcePath:resourcePath queryParameters:queryParameters] autorelease]; } -+ (id)URLWithBaseURLString:(NSString *)baseURLString { ++ (id)URLWithBaseURLString:(NSString *)baseURLString +{ return [self URLWithBaseURLString:baseURLString resourcePath:nil queryParameters:nil]; } -+ (id)URLWithBaseURLString:(NSString *)baseURLString resourcePath:(NSString *)resourcePath { ++ (id)URLWithBaseURLString:(NSString *)baseURLString resourcePath:(NSString *)resourcePath +{ return [self URLWithBaseURLString:baseURLString resourcePath:resourcePath queryParameters:nil]; } -+ (id)URLWithBaseURLString:(NSString *)baseURLString resourcePath:(NSString *)resourcePath queryParameters:(NSDictionary *)queryParameters { ++ (id)URLWithBaseURLString:(NSString *)baseURLString resourcePath:(NSString *)resourcePath queryParameters:(NSDictionary *)queryParameters +{ return [self URLWithBaseURL:[NSURL URLWithString:baseURLString] resourcePath:resourcePath queryParameters:queryParameters]; } // Designated initializer. Note this diverges from NSURL due to a bug in Cocoa. We can't // call initWithString:relativeToURL: from a subclass. -- (id)initWithBaseURL:(NSURL *)theBaseURL resourcePath:(NSString *)theResourcePath queryParameters:(NSDictionary *)theQueryParameters { +- (id)initWithBaseURL:(NSURL *)theBaseURL resourcePath:(NSString *)theResourcePath queryParameters:(NSDictionary *)theQueryParameters +{ // Merge any existing query parameters with the incoming dictionary NSDictionary *resourcePathQueryParameters = [theResourcePath queryParameters]; NSMutableDictionary *mergedQueryParameters = [NSMutableDictionary dictionaryWithDictionary:[theBaseURL queryParameters]]; @@ -73,11 +80,11 @@ - (id)initWithBaseURL:(NSURL *)theBaseURL resourcePath:(NSString *)theResourcePa NSString *resourcePathWithoutQueryString = (queryCharacterRange.location == NSNotFound) ? theResourcePath : [theResourcePath substringToIndex:queryCharacterRange.location]; NSString *baseURLPath = [[theBaseURL path] isEqualToString:@"/"] ? @"" : [[theBaseURL path] stringByStandardizingPath]; NSString *completePath = resourcePathWithoutQueryString ? [baseURLPath stringByAppendingString:resourcePathWithoutQueryString] : baseURLPath; - NSString* completePathWithQuery = [completePath stringByAppendingQueryParameters:mergedQueryParameters]; + NSString *completePathWithQuery = [completePath stringByAppendingQueryParameters:mergedQueryParameters]; // NOTE: You can't safely use initWithString:relativeToURL: in a NSURL subclass, see http://www.openradar.me/9729706 // So we unfortunately convert into an NSURL before going back into an NSString -> RKURL - NSURL* completeURL = [NSURL URLWithString:completePathWithQuery relativeToURL:theBaseURL]; + NSURL *completeURL = [NSURL URLWithString:completePathWithQuery relativeToURL:theBaseURL]; if (!completeURL) { RKLogError(@"Failed to build RKURL by appending resourcePath and query parameters '%@' to baseURL '%@'", theResourcePath, theBaseURL); [self release]; @@ -93,7 +100,8 @@ - (id)initWithBaseURL:(NSURL *)theBaseURL resourcePath:(NSString *)theResourcePa return self; } -- (void)dealloc { +- (void)dealloc +{ [baseURL release]; baseURL = nil; [resourcePath release]; @@ -102,30 +110,36 @@ - (void)dealloc { [super dealloc]; } -- (NSDictionary *)queryParameters { +- (NSDictionary *)queryParameters +{ if (self.query) { return [NSDictionary dictionaryWithURLEncodedString:self.query]; } return nil; } -- (RKURL *)URLByAppendingResourcePath:(NSString *)theResourcePath { +- (RKURL *)URLByAppendingResourcePath:(NSString *)theResourcePath +{ return [RKURL URLWithBaseURL:self resourcePath:theResourcePath]; } -- (RKURL *)URLByAppendingResourcePath:(NSString *)theResourcePath queryParameters:(NSDictionary *)theQueryParameters { +- (RKURL *)URLByAppendingResourcePath:(NSString *)theResourcePath queryParameters:(NSDictionary *)theQueryParameters +{ return [RKURL URLWithBaseURL:self resourcePath:theResourcePath queryParameters:theQueryParameters]; } -- (RKURL *)URLByAppendingQueryParameters:(NSDictionary *)theQueryParameters { +- (RKURL *)URLByAppendingQueryParameters:(NSDictionary *)theQueryParameters +{ return [RKURL URLWithBaseURL:self resourcePath:nil queryParameters:theQueryParameters]; } -- (RKURL *)URLByReplacingResourcePath:(NSString *)newResourcePath { +- (RKURL *)URLByReplacingResourcePath:(NSString *)newResourcePath +{ return [RKURL URLWithBaseURL:self.baseURL resourcePath:newResourcePath]; } -- (RKURL *)URLByInterpolatingResourcePathWithObject:(id)object { +- (RKURL *)URLByInterpolatingResourcePathWithObject:(id)object +{ return [self URLByReplacingResourcePath:[self.resourcePath interpolateWithObject:object]]; } @@ -136,11 +150,13 @@ - (RKURL *)URLByInterpolatingResourcePathWithObject:(id)object { with a baseURL == self. Otherwise appending/replacing resourcePath will not work. */ -+ (id)URLWithString:(NSString *)URLString { ++ (id)URLWithString:(NSString *)URLString +{ return [self URLWithBaseURLString:URLString]; } -- (id)initWithString:(NSString *)URLString { +- (id)initWithString:(NSString *)URLString +{ self = [super initWithString:URLString]; if (self) { self.baseURL = self; diff --git a/Code/ObjectMapping/RKDynamicObjectMapping.h b/Code/ObjectMapping/RKDynamicObjectMapping.h index c0c70b3cd5..e2c00f682d 100644 --- a/Code/ObjectMapping/RKDynamicObjectMapping.h +++ b/Code/ObjectMapping/RKDynamicObjectMapping.h @@ -42,10 +42,6 @@ typedef RKObjectMapping *(^RKDynamicObjectMappingDelegateBlock)(id); */ @interface RKDynamicObjectMapping : RKObjectMappingDefinition { NSMutableArray *_matchers; - id _delegate; - #ifdef NS_BLOCKS_AVAILABLE - RKDynamicObjectMappingDelegateBlock _objectMappingForDataBlock; - #endif } /** @@ -87,7 +83,7 @@ typedef RKObjectMapping *(^RKDynamicObjectMappingDelegateBlock)(id); the gender of the person. When the gender is 'male', we want to use the Boy class and when then the gender is 'female' we want to use the Girl class. We might define our dynamic mapping like so: - RKDynamicObjectMapping* mapping = [RKDynamicObjectMapping dynamicMapping]; + RKDynamicObjectMapping *mapping = [RKDynamicObjectMapping dynamicMapping]; [mapping setObjectMapping:boyMapping whenValueOfKeyPath:@"gender" isEqualTo:@"male"]; [mapping setObjectMapping:boyMapping whenValueOfKeyPath:@"gender" isEqualTo:@"female"]; */ diff --git a/Code/ObjectMapping/RKDynamicObjectMapping.m b/Code/ObjectMapping/RKDynamicObjectMapping.m index 1ed3d39652..6d418f0f87 100644 --- a/Code/ObjectMapping/RKDynamicObjectMapping.m +++ b/Code/ObjectMapping/RKDynamicObjectMapping.m @@ -32,25 +32,29 @@ @implementation RKDynamicObjectMapping @synthesize delegate = _delegate; @synthesize objectMappingForDataBlock = _objectMappingForDataBlock; -+ (RKDynamicObjectMapping*)dynamicMapping { ++ (RKDynamicObjectMapping *)dynamicMapping +{ return [[self new] autorelease]; } #if NS_BLOCKS_AVAILABLE -+ (RKDynamicObjectMapping *)dynamicMappingUsingBlock:(void(^)(RKDynamicObjectMapping *))block { - RKDynamicObjectMapping* mapping = [self dynamicMapping]; ++ (RKDynamicObjectMapping *)dynamicMappingUsingBlock:(void(^)(RKDynamicObjectMapping *))block +{ + RKDynamicObjectMapping *mapping = [self dynamicMapping]; block(mapping); return mapping; } -+ (RKDynamicObjectMapping*)dynamicMappingWithBlock:(void(^)(RKDynamicObjectMapping*))block { ++ (RKDynamicObjectMapping *)dynamicMappingWithBlock:(void(^)(RKDynamicObjectMapping *))block +{ return [self dynamicMappingUsingBlock:block]; } #endif -- (id)init { +- (id)init +{ self = [super init]; if (self) { _matchers = [NSMutableArray new]; @@ -59,26 +63,29 @@ - (id)init { return self; } -- (void)dealloc { +- (void)dealloc +{ [_matchers release]; [super dealloc]; } -- (void)setObjectMapping:(RKObjectMapping*)objectMapping whenValueOfKeyPath:(NSString*)keyPath isEqualTo:(id)value { +- (void)setObjectMapping:(RKObjectMapping *)objectMapping whenValueOfKeyPath:(NSString *)keyPath isEqualTo:(id)value +{ RKLogDebug(@"Adding dynamic object mapping for key '%@' with value '%@' to destination class: %@", keyPath, value, NSStringFromClass(objectMapping.objectClass)); - RKDynamicObjectMappingMatcher* matcher = [[RKDynamicObjectMappingMatcher alloc] initWithKey:keyPath value:value objectMapping:objectMapping]; + RKDynamicObjectMappingMatcher *matcher = [[RKDynamicObjectMappingMatcher alloc] initWithKey:keyPath value:value objectMapping:objectMapping]; [_matchers addObject:matcher]; [matcher release]; } -- (RKObjectMapping*)objectMappingForDictionary:(NSDictionary*)data { +- (RKObjectMapping *)objectMappingForDictionary:(NSDictionary *)data +{ NSAssert([data isKindOfClass:[NSDictionary class]], @"Dynamic object mapping can only be performed on NSDictionary mappables, got %@", NSStringFromClass([data class])); - RKObjectMapping* mapping = nil; + RKObjectMapping *mapping = nil; RKLogTrace(@"Performing dynamic object mapping for mappable data: %@", data); // Consult the declarative matchers first - for (RKDynamicObjectMappingMatcher* matcher in _matchers) { + for (RKDynamicObjectMappingMatcher *matcher in _matchers) { if ([matcher isMatchForData:data]) { RKLogTrace(@"Found declarative match for data: %@.", [matcher matchDescription]); return matcher.objectMapping; diff --git a/Code/ObjectMapping/RKDynamicObjectMappingMatcher.h b/Code/ObjectMapping/RKDynamicObjectMappingMatcher.h index 0a92b53362..5691214d3b 100644 --- a/Code/ObjectMapping/RKDynamicObjectMappingMatcher.h +++ b/Code/ObjectMapping/RKDynamicObjectMappingMatcher.h @@ -11,20 +11,18 @@ @interface RKDynamicObjectMappingMatcher : NSObject { - NSString* _keyPath; + NSString *_keyPath; id _value; - RKObjectMapping* _objectMapping; - NSString* _primaryKeyAttribute; BOOL (^_isMatchForDataBlock)(id data); } -@property (nonatomic, readonly) RKObjectMapping* objectMapping; -@property (nonatomic, readonly) NSString* primaryKeyAttribute; +@property (nonatomic, readonly) RKObjectMapping *objectMapping; +@property (nonatomic, readonly) NSString *primaryKeyAttribute; -- (id)initWithKey:(NSString*)key value:(id)value objectMapping:(RKObjectMapping*)objectMapping; -- (id)initWithKey:(NSString*)key value:(id)value primaryKeyAttribute:(NSString*)primaryKeyAttribute; -- (id)initWithPrimaryKeyAttribute:(NSString*)primaryKeyAttribute evaluationBlock:(BOOL (^)(id data))block; +- (id)initWithKey:(NSString *)key value:(id)value objectMapping:(RKObjectMapping *)objectMapping; +- (id)initWithKey:(NSString *)key value:(id)value primaryKeyAttribute:(NSString *)primaryKeyAttribute; +- (id)initWithPrimaryKeyAttribute:(NSString *)primaryKeyAttribute evaluationBlock:(BOOL (^)(id data))block; - (BOOL)isMatchForData:(id)data; -- (NSString*)matchDescription; +- (NSString *)matchDescription; @end diff --git a/Code/ObjectMapping/RKDynamicObjectMappingMatcher.m b/Code/ObjectMapping/RKDynamicObjectMappingMatcher.m index 0fcecff9a4..2c708051bc 100644 --- a/Code/ObjectMapping/RKDynamicObjectMappingMatcher.m +++ b/Code/ObjectMapping/RKDynamicObjectMappingMatcher.m @@ -19,7 +19,8 @@ @implementation RKDynamicObjectMappingMatcher @synthesize objectMapping = _objectMapping; @synthesize primaryKeyAttribute = _primaryKeyAttribute; -- (id)initWithKey:(NSString*)key value:(id)value objectMapping:(RKObjectMapping*)objectMapping { +- (id)initWithKey:(NSString *)key value:(id)value objectMapping:(RKObjectMapping *)objectMapping +{ self = [super init]; if (self) { _keyPath = [key retain]; @@ -30,7 +31,8 @@ - (id)initWithKey:(NSString*)key value:(id)value objectMapping:(RKObjectMapping* return self; } -- (id)initWithKey:(NSString*)key value:(id)value primaryKeyAttribute:(NSString*)primaryKeyAttribute { +- (id)initWithKey:(NSString *)key value:(id)value primaryKeyAttribute:(NSString *)primaryKeyAttribute +{ self = [super init]; if (self) { _keyPath = [key retain]; @@ -41,7 +43,8 @@ - (id)initWithKey:(NSString*)key value:(id)value primaryKeyAttribute:(NSString*) return self; } -- (id)initWithPrimaryKeyAttribute:(NSString*)primaryKeyAttribute evaluationBlock:(BOOL (^)(id data))block { +- (id)initWithPrimaryKeyAttribute:(NSString *)primaryKeyAttribute evaluationBlock:(BOOL (^)(id data))block +{ self = [super init]; if (self) { _primaryKeyAttribute = [primaryKeyAttribute retain]; @@ -50,7 +53,8 @@ - (id)initWithPrimaryKeyAttribute:(NSString*)primaryKeyAttribute evaluationBlock return self; } -- (void)dealloc { +- (void)dealloc +{ [_keyPath release]; [_value release]; [_objectMapping release]; @@ -61,14 +65,16 @@ - (void)dealloc { [super dealloc]; } -- (BOOL)isMatchForData:(id)data { +- (BOOL)isMatchForData:(id)data +{ if (_isMatchForDataBlock) { return _isMatchForDataBlock(data); } return RKObjectIsValueEqualToValue([data valueForKeyPath:_keyPath], _value); } -- (NSString*)matchDescription { +- (NSString *)matchDescription +{ if (_isMatchForDataBlock) { return @"No description available. Using block to perform match."; } diff --git a/Code/ObjectMapping/RKErrorMessage.h b/Code/ObjectMapping/RKErrorMessage.h index 5a20a993fa..928e1a1210 100644 --- a/Code/ObjectMapping/RKErrorMessage.h +++ b/Code/ObjectMapping/RKErrorMessage.h @@ -23,13 +23,11 @@ /** A destination class for mapping simple remote error messages. */ -@interface RKErrorMessage : NSObject { - NSString* _errorMessage; -} +@interface RKErrorMessage : NSObject /** The error message string mapped from the response payload */ -@property (nonatomic, retain) NSString* errorMessage; +@property (nonatomic, retain) NSString *errorMessage; @end diff --git a/Code/ObjectMapping/RKErrorMessage.m b/Code/ObjectMapping/RKErrorMessage.m index 6df33abada..966ffdf99d 100644 --- a/Code/ObjectMapping/RKErrorMessage.m +++ b/Code/ObjectMapping/RKErrorMessage.m @@ -25,12 +25,14 @@ @implementation RKErrorMessage @synthesize errorMessage = _errorMessage; -- (void)dealloc { +- (void)dealloc +{ [_errorMessage release]; [super dealloc]; } -- (NSString*)description { +- (NSString *)description +{ return _errorMessage; } diff --git a/Code/ObjectMapping/RKMappingOperationQueue.m b/Code/ObjectMapping/RKMappingOperationQueue.m index 7f36a3eb0a..f0ef99685b 100644 --- a/Code/ObjectMapping/RKMappingOperationQueue.m +++ b/Code/ObjectMapping/RKMappingOperationQueue.m @@ -10,7 +10,8 @@ @implementation RKMappingOperationQueue -- (id)init { +- (id)init +{ self = [super init]; if (self) { _operations = [NSMutableArray new]; @@ -19,29 +20,35 @@ - (id)init { return self; } -- (void)dealloc { +- (void)dealloc +{ [_operations release]; [super dealloc]; } -- (void)addOperation:(NSOperation *)op { +- (void)addOperation:(NSOperation *)op +{ [_operations addObject:op]; } -- (void)addOperationWithBlock:(void (^)(void))block { +- (void)addOperationWithBlock:(void (^)(void))block +{ NSBlockOperation *blockOperation = [NSBlockOperation blockOperationWithBlock:block]; [_operations addObject:blockOperation]; } -- (NSArray *)operations { +- (NSArray *)operations +{ return [NSArray arrayWithArray:_operations]; } -- (NSUInteger)operationCount { +- (NSUInteger)operationCount +{ return [_operations count]; } -- (void)waitUntilAllOperationsAreFinished { +- (void)waitUntilAllOperationsAreFinished +{ for (NSOperation *operation in _operations) { [operation start]; } diff --git a/Code/ObjectMapping/RKObjectAttributeMapping.h b/Code/ObjectMapping/RKObjectAttributeMapping.h index 93e859ba23..8dec7bb3a8 100644 --- a/Code/ObjectMapping/RKObjectAttributeMapping.h +++ b/Code/ObjectMapping/RKObjectAttributeMapping.h @@ -21,10 +21,7 @@ #import // Defines the rules for mapping a particular element -@interface RKObjectAttributeMapping : NSObject { - NSString *_sourceKeyPath; - NSString *_destinationKeyPath; -} +@interface RKObjectAttributeMapping : NSObject @property (nonatomic, retain) NSString *sourceKeyPath; @property (nonatomic, retain) NSString *destinationKeyPath; diff --git a/Code/ObjectMapping/RKObjectAttributeMapping.m b/Code/ObjectMapping/RKObjectAttributeMapping.m index d92dcee9ed..01c541e901 100644 --- a/Code/ObjectMapping/RKObjectAttributeMapping.m +++ b/Code/ObjectMapping/RKObjectAttributeMapping.m @@ -20,7 +20,7 @@ #import "RKObjectAttributeMapping.h" -extern NSString* const RKObjectMappingNestingAttributeKeyName; +extern NSString * const RKObjectMappingNestingAttributeKeyName; @implementation RKObjectAttributeMapping @@ -30,7 +30,8 @@ @implementation RKObjectAttributeMapping /** @private */ -- (id)initWithSourceKeyPath:(NSString *)sourceKeyPath andDestinationKeyPath:(NSString *)destinationKeyPath { +- (id)initWithSourceKeyPath:(NSString *)sourceKeyPath andDestinationKeyPath:(NSString *)destinationKeyPath +{ NSAssert(sourceKeyPath != nil, @"Cannot define an element mapping an element name to map from"); NSAssert(destinationKeyPath != nil, @"Cannot define an element mapping without a property to apply the value to"); self = [super init]; @@ -42,28 +43,33 @@ - (id)initWithSourceKeyPath:(NSString *)sourceKeyPath andDestinationKeyPath:(NSS return self; } -- (id)copyWithZone:(NSZone *)zone { - RKObjectAttributeMapping* copy = [[[self class] allocWithZone:zone] initWithSourceKeyPath:self.sourceKeyPath andDestinationKeyPath:self.destinationKeyPath]; +- (id)copyWithZone:(NSZone *)zone +{ + RKObjectAttributeMapping *copy = [[[self class] allocWithZone:zone] initWithSourceKeyPath:self.sourceKeyPath andDestinationKeyPath:self.destinationKeyPath]; return copy; } -- (void)dealloc { +- (void)dealloc +{ [_sourceKeyPath release]; [_destinationKeyPath release]; [super dealloc]; } -- (NSString *)description { +- (NSString *)description +{ return [NSString stringWithFormat:@"RKObjectKeyPathMapping: %@ => %@", self.sourceKeyPath, self.destinationKeyPath]; } -+ (RKObjectAttributeMapping *)mappingFromKeyPath:(NSString *)sourceKeyPath toKeyPath:(NSString *)destinationKeyPath { ++ (RKObjectAttributeMapping *)mappingFromKeyPath:(NSString *)sourceKeyPath toKeyPath:(NSString *)destinationKeyPath +{ RKObjectAttributeMapping *mapping = [[self alloc] initWithSourceKeyPath:sourceKeyPath andDestinationKeyPath:destinationKeyPath]; return [mapping autorelease]; } -- (BOOL)isMappingForKeyOfNestedDictionary { +- (BOOL)isMappingForKeyOfNestedDictionary +{ return ([self.sourceKeyPath isEqualToString:RKObjectMappingNestingAttributeKeyName]); } diff --git a/Code/ObjectMapping/RKObjectLoader.h b/Code/ObjectMapping/RKObjectLoader.h index e80453f2b1..c65baab5be 100644 --- a/Code/ObjectMapping/RKObjectLoader.h +++ b/Code/ObjectMapping/RKObjectLoader.h @@ -136,9 +136,7 @@ typedef void(^RKObjectLoaderDidLoadObjectsDictionaryBlock)(NSDictionary *diction * includes Core Data specific mapping logic. */ @interface RKObjectLoader : RKRequest { - id _sourceObject; - id _targetObject; - dispatch_queue_t _mappingQueue; + NSObject* _targetObject; } /** @@ -285,6 +283,6 @@ typedef void(^RKObjectLoaderDidLoadObjectsDictionaryBlock)(NSDictionary *diction @class RKObjectManager; @interface RKObjectLoader (Deprecations) -+ (id)loaderWithResourcePath:(NSString*)resourcePath objectManager:(RKObjectManager*)objectManager delegate:(id)delegate DEPRECATED_ATTRIBUTE; -- (id)initWithResourcePath:(NSString*)resourcePath objectManager:(RKObjectManager*)objectManager delegate:(id)delegate DEPRECATED_ATTRIBUTE; ++ (id)loaderWithResourcePath:(NSString *)resourcePath objectManager:(RKObjectManager *)objectManager delegate:(id)delegate DEPRECATED_ATTRIBUTE; +- (id)initWithResourcePath:(NSString *)resourcePath objectManager:(RKObjectManager *)objectManager delegate:(id)delegate DEPRECATED_ATTRIBUTE; @end diff --git a/Code/ObjectMapping/RKObjectLoader.m b/Code/ObjectMapping/RKObjectLoader.m index eed310762f..c51dfe2c36 100644 --- a/Code/ObjectMapping/RKObjectLoader.m +++ b/Code/ObjectMapping/RKObjectLoader.m @@ -61,11 +61,13 @@ @implementation RKObjectLoader @dynamic loading; @dynamic response; -+ (id)loaderWithURL:(RKURL *)URL mappingProvider:(RKObjectMappingProvider *)mappingProvider { ++ (id)loaderWithURL:(RKURL *)URL mappingProvider:(RKObjectMappingProvider *)mappingProvider +{ return [[[self alloc] initWithURL:URL mappingProvider:mappingProvider] autorelease]; } -- (id)initWithURL:(RKURL *)URL mappingProvider:(RKObjectMappingProvider *)mappingProvider { +- (id)initWithURL:(RKURL *)URL mappingProvider:(RKObjectMappingProvider *)mappingProvider +{ self = [super initWithURL:URL]; if (self) { _mappingProvider = [mappingProvider retain]; @@ -75,13 +77,14 @@ - (id)initWithURL:(RKURL *)URL mappingProvider:(RKObjectMappingProvider *)mappin return self; } -- (void)dealloc { +- (void)dealloc +{ [_mappingProvider release]; _mappingProvider = nil; [_sourceObject release]; _sourceObject = nil; [_targetObject release]; - _targetObject = nil; + _targetObject = nil; [_objectMapping release]; _objectMapping = nil; [_result release]; @@ -102,13 +105,15 @@ - (void)dealloc { [super dealloc]; } -- (void)reset { +- (void)reset +{ [super reset]; [_result release]; _result = nil; } -- (void)informDelegateOfError:(NSError *)error { +- (void)informDelegateOfError:(NSError *)error +{ [(NSObject*)_delegate objectLoader:self didFailWithError:error]; if (self.onDidFailWithError) { @@ -120,10 +125,11 @@ - (void)informDelegateOfError:(NSError *)error { // NOTE: This method is significant because the notifications posted are used by // RKRequestQueue to remove requests from the queue. All requests need to be finalized. -- (void)finalizeLoad:(BOOL)successful { +- (void)finalizeLoad:(BOOL)successful +{ self.loading = NO; self.loaded = successful; - + if ([self.delegate respondsToSelector:@selector(objectLoaderDidFinishLoading:)]) { [(NSObject*)self.delegate performSelectorOnMainThread:@selector(objectLoaderDidFinishLoading:) withObject:self waitUntilDone:YES]; @@ -133,10 +139,11 @@ - (void)finalizeLoad:(BOOL)successful { } // Invoked on the main thread. Inform the delegate. -- (void)informDelegateOfObjectLoadWithResultDictionary:(NSDictionary*)resultDictionary { +- (void)informDelegateOfObjectLoadWithResultDictionary:(NSDictionary *)resultDictionary +{ NSAssert([NSThread isMainThread], @"RKObjectLoaderDelegate callbacks must occur on the main thread"); - RKObjectMappingResult* result = [RKObjectMappingResult mappingResultWithDictionary:resultDictionary]; + RKObjectMappingResult *result = [RKObjectMappingResult mappingResultWithDictionary:resultDictionary]; // Dictionary callback if ([self.delegate respondsToSelector:@selector(objectLoader:didLoadObjectDictionary:)]) { @@ -175,14 +182,16 @@ - (void)informDelegateOfObjectLoadWithResultDictionary:(NSDictionary*)resultDict at thread boundaries. @protected */ -- (void)processMappingResult:(RKObjectMappingResult*)result { +- (void)processMappingResult:(RKObjectMappingResult *)result +{ NSAssert(_sentSynchronously || ![NSThread isMainThread], @"Mapping result processing should occur on a background thread"); [self performSelectorOnMainThread:@selector(informDelegateOfObjectLoadWithResultDictionary:) withObject:[result asDictionary] waitUntilDone:YES]; } #pragma mark - Response Object Mapping -- (RKObjectMappingResult*)mapResponseWithMappingProvider:(RKObjectMappingProvider*)mappingProvider toObject:(id)targetObject inContext:(RKObjectMappingProviderContext)context error:(NSError**)error { +- (RKObjectMappingResult *)mapResponseWithMappingProvider:(RKObjectMappingProvider *)mappingProvider toObject:(id)targetObject inContext:(RKObjectMappingProviderContext)context error:(NSError **)error +{ id parser = [[RKParserRegistry sharedRegistry] parserForMIMEType:self.response.MIMEType]; NSAssert1(parser, @"Cannot perform object load without a parser for MIME Type '%@'", self.response.MIMEType); @@ -211,11 +220,11 @@ - (RKObjectMappingResult*)mapResponseWithMappingProvider:(RKObjectMappingProvide [(NSObject*)self.delegate objectLoader:self willMapData:&parsedData]; } - RKObjectMapper* mapper = [RKObjectMapper mapperWithObject:parsedData mappingProvider:mappingProvider]; + RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:parsedData mappingProvider:mappingProvider]; mapper.targetObject = targetObject; mapper.delegate = self; mapper.context = context; - RKObjectMappingResult* result = [mapper performMapping]; + RKObjectMappingResult *result = [mapper performMapping]; // Log any mapping errors if (mapper.errorCount > 0) { @@ -232,7 +241,8 @@ - (RKObjectMappingResult*)mapResponseWithMappingProvider:(RKObjectMappingProvide return result; } -- (RKObjectMappingDefinition *)configuredObjectMapping { +- (RKObjectMappingDefinition *)configuredObjectMapping +{ if (self.objectMapping) { return self.objectMapping; } @@ -240,10 +250,11 @@ - (RKObjectMappingDefinition *)configuredObjectMapping { return [self.mappingProvider objectMappingForResourcePath:self.resourcePath]; } -- (RKObjectMappingResult*)performMapping:(NSError**)error { +- (RKObjectMappingResult *)performMapping:(NSError **)error +{ NSAssert(_sentSynchronously || ![NSThread isMainThread], @"Mapping should occur on a background thread"); - RKObjectMappingProvider* mappingProvider; + RKObjectMappingProvider *mappingProvider; RKObjectMappingDefinition *configuredObjectMapping = [self configuredObjectMapping]; if (configuredObjectMapping) { mappingProvider = [RKObjectMappingProvider mappingProvider]; @@ -260,10 +271,11 @@ - (RKObjectMappingResult*)performMapping:(NSError**)error { return [self mapResponseWithMappingProvider:mappingProvider toObject:self.targetObject inContext:RKObjectMappingProviderContextObjectsByKeyPath error:error]; } -- (void)performMappingInDispatchQueue { +- (void)performMappingInDispatchQueue +{ NSAssert(self.mappingQueue, @"mappingQueue cannot be nil"); dispatch_async(self.mappingQueue, ^{ - NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; RKLogDebug(@"Beginning object mapping activities within GCD queue labeled: %s", dispatch_queue_get_label(self.mappingQueue)); NSError *error = nil; @@ -279,7 +291,8 @@ - (void)performMappingInDispatchQueue { }); } -- (BOOL)canParseMIMEType:(NSString*)MIMEType { +- (BOOL)canParseMIMEType:(NSString *)MIMEType +{ if ([[RKParserRegistry sharedRegistry] parserForMIMEType:self.response.MIMEType]) { return YES; } @@ -288,7 +301,8 @@ - (BOOL)canParseMIMEType:(NSString*)MIMEType { return NO; } -- (BOOL)isResponseMappable { +- (BOOL)isResponseMappable +{ if ([self.response isServiceUnavailable]) { [[NSNotificationCenter defaultCenter] postNotificationName:RKServiceDidBecomeUnavailableNotification object:self]; } @@ -312,8 +326,8 @@ - (BOOL)isResponseMappable { return NO; } else if (NO == [self canParseMIMEType:[self.response MIMEType]]) { // We can't parse the response, it's unmappable regardless of the status code - RKLogWarning(@"Encountered unexpected response with status code: %ld (MIME Type: %@ -> URL: %@)", (long) self.response.statusCode, self.response.MIMEType, self.URL); - NSError* error = [NSError errorWithDomain:RKErrorDomain code:RKObjectLoaderUnexpectedResponseError userInfo:nil]; + RKLogWarning(@"Encountered unexpected response with status code: %ld (MIME Type: %@ -> URL: %@)", (long)self.response.statusCode, self.response.MIMEType, self.URL); + NSError *error = [NSError errorWithDomain:RKErrorDomain code:RKObjectLoaderUnexpectedResponseError userInfo:nil]; if ([_delegate respondsToSelector:@selector(objectLoaderDidLoadUnexpectedResponse:)]) { [(NSObject*)_delegate objectLoaderDidLoadUnexpectedResponse:self]; } else { @@ -334,7 +348,8 @@ - (BOOL)isResponseMappable { return YES; } -- (void)handleResponseError { +- (void)handleResponseError +{ // Since we are mapping what we know to be an error response, we don't want to map the result back onto our // target object NSError *error = nil; @@ -352,12 +367,13 @@ - (void)handleResponseError { #pragma mark - RKRequest & RKRequestDelegate methods // Invoked just before request hits the network -- (BOOL)prepareURLRequest { +- (BOOL)prepareURLRequest +{ if ((self.sourceObject && self.params == nil) && (self.method == RKRequestMethodPOST || self.method == RKRequestMethodPUT)) { NSAssert(self.serializationMapping, @"You must provide a serialization mapping for objects of type '%@'", NSStringFromClass([self.sourceObject class])); RKLogDebug(@"POST or PUT request for source object %@, serializing to MIME Type %@ for transport...", self.sourceObject, self.serializationMIMEType); - RKObjectSerializer* serializer = [RKObjectSerializer serializerWithObject:self.sourceObject mapping:self.serializationMapping]; - NSError* error = nil; + RKObjectSerializer *serializer = [RKObjectSerializer serializerWithObject:self.sourceObject mapping:self.serializationMapping]; + NSError *error = nil; id params = [serializer serializationForMIMEType:self.serializationMIMEType error:&error]; if (error) { @@ -383,9 +399,10 @@ - (BOOL)prepareURLRequest { return [super prepareURLRequest]; } -- (void)didFailLoadWithError:(NSError *)error { +- (void)didFailLoadWithError:(NSError *)error +{ NSParameterAssert(error); - NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; if (_cachePolicy & RKRequestCachePolicyLoadOnError && [self.cache hasResponseForRequest:self]) { @@ -402,12 +419,12 @@ - (void)didFailLoadWithError:(NSError *)error { // If we failed due to a transport error or before we have a response, the request itself failed if (!self.response || [self.response isFailure]) { - NSDictionary* userInfo = [NSDictionary dictionaryWithObject:error forKey:RKRequestDidFailWithErrorNotificationUserInfoErrorKey]; + NSDictionary *userInfo = [NSDictionary dictionaryWithObject:error forKey:RKRequestDidFailWithErrorNotificationUserInfoErrorKey]; [[NSNotificationCenter defaultCenter] postNotificationName:RKRequestDidFailWithErrorNotification object:self userInfo:userInfo]; } - + if (! self.isCancelled) { [self informDelegateOfError:error]; } @@ -419,7 +436,8 @@ - (void)didFailLoadWithError:(NSError *)error { } // NOTE: We do NOT call super here. We are overloading the default behavior from RKRequest -- (void)didFinishLoad:(RKResponse*)response { +- (void)didFinishLoad:(RKResponse *)response +{ NSAssert([NSThread isMainThread], @"RKObjectLoaderDelegate callbacks must occur on the main thread"); self.response = response; @@ -442,7 +460,7 @@ - (void)didFinishLoad:(RKResponse*)response { } // Post the notification - NSDictionary* userInfo = [NSDictionary dictionaryWithObject:self.response + NSDictionary *userInfo = [NSDictionary dictionaryWithObject:self.response forKey:RKRequestDidLoadResponseNotificationUserInfoResponseKey]; [[NSNotificationCenter defaultCenter] postNotificationName:RKRequestDidLoadResponseNotification object:self @@ -451,7 +469,7 @@ - (void)didFinishLoad:(RKResponse*)response { if ([self isResponseMappable]) { // Determine if we are synchronous here or not. if (_sentSynchronously) { - NSError* error = nil; + NSError *error = nil; _result = [[self performMapping:&error] retain]; if (self.result) { [self processMappingResult:self.result]; @@ -464,7 +482,8 @@ - (void)didFinishLoad:(RKResponse*)response { } } -- (void)setMappingQueue:(dispatch_queue_t)newMappingQueue { +- (void)setMappingQueue:(dispatch_queue_t)newMappingQueue +{ if (_mappingQueue) { dispatch_release(_mappingQueue); _mappingQueue = nil; @@ -478,11 +497,13 @@ - (void)setMappingQueue:(dispatch_queue_t)newMappingQueue { // Proxy the delegate property back to our superclass implementation. The object loader should // really not be a subclass of RKRequest. -- (void)setDelegate:(id)delegate { +- (void)setDelegate:(id)delegate +{ [super setDelegate:delegate]; } -- (id)delegate { +- (id)delegate +{ return (id) [super delegate]; } @@ -490,11 +511,13 @@ - (void)setDelegate:(id)delegate { @implementation RKObjectLoader (Deprecations) -+ (id)loaderWithResourcePath:(NSString*)resourcePath objectManager:(RKObjectManager*)objectManager delegate:(id)delegate { ++ (id)loaderWithResourcePath:(NSString *)resourcePath objectManager:(RKObjectManager *)objectManager delegate:(id)delegate +{ return [[[self alloc] initWithResourcePath:resourcePath objectManager:objectManager delegate:delegate] autorelease]; } -- (id)initWithResourcePath:(NSString*)resourcePath objectManager:(RKObjectManager*)objectManager delegate:(id)theDelegate { +- (id)initWithResourcePath:(NSString *)resourcePath objectManager:(RKObjectManager *)objectManager delegate:(id)theDelegate +{ if ((self = [self initWithURL:[objectManager.baseURL URLByAppendingResourcePath:resourcePath] mappingProvider:objectManager.mappingProvider])) { [objectManager.client configureRequest:self]; _delegate = theDelegate; diff --git a/Code/ObjectMapping/RKObjectLoader_Internals.h b/Code/ObjectMapping/RKObjectLoader_Internals.h index 7f745bed8b..a171114bac 100644 --- a/Code/ObjectMapping/RKObjectLoader_Internals.h +++ b/Code/ObjectMapping/RKObjectLoader_Internals.h @@ -22,12 +22,12 @@ @interface RKObjectLoader (Internals) -@property (nonatomic, readonly) RKClient* client; +@property (nonatomic, readonly) RKClient *client; - (void)handleTargetObject; -- (void)informDelegateOfObjectLoadWithResultDictionary:(NSDictionary*)dictionary; +- (void)informDelegateOfObjectLoadWithResultDictionary:(NSDictionary *)dictionary; - (void)performMappingOnBackgroundThread; - (BOOL)isResponseMappable; -- (void)finalizeLoad:(BOOL)successful error:(NSError*)error; +- (void)finalizeLoad:(BOOL)successful error:(NSError *)error; @end diff --git a/Code/ObjectMapping/RKObjectManager.h b/Code/ObjectMapping/RKObjectManager.h index fc6f3adc23..6cf728fcb5 100644 --- a/Code/ObjectMapping/RKObjectManager.h +++ b/Code/ObjectMapping/RKObjectManager.h @@ -32,12 +32,12 @@ /** Posted when the object managed has transitioned to the offline state */ -extern NSString* const RKObjectManagerDidBecomeOfflineNotification; +extern NSString * const RKObjectManagerDidBecomeOfflineNotification; /** Posted when the object managed has transitioned to the online state */ -extern NSString* const RKObjectManagerDidBecomeOnlineNotification; +extern NSString * const RKObjectManagerDidBecomeOnlineNotification; typedef enum { RKObjectManagerNetworkStatusUnknown, @@ -93,8 +93,8 @@ typedef enum { Mappings are registered by constructing instances of RKObjectMapping and registering them with the provider: ` - RKObjectManager* manager = [RKObjectManager managerWithBaseURL:myBaseURL]; - RKObjectMapping* articleMapping = [RKObjectMapping mappingForClass:[Article class]]; + RKObjectManager *manager = [RKObjectManager managerWithBaseURL:myBaseURL]; + RKObjectMapping *articleMapping = [RKObjectMapping mappingForClass:[Article class]]; [mapping mapAttributes:@"title", @"body", @"publishedAt", nil]; [manager.mappingProvider setObjectMapping:articleMapping forKeyPath:@"article"]; @@ -366,7 +366,7 @@ typedef enum { For example: - (void)loadObjectUsingBlockExample { - [[RKObjectManager sharedManager] loadObjectsAtResourcePath:@"/monkeys.json" usingBlock:^(RKObjectLoader* loader) { + [[RKObjectManager sharedManager] loadObjectsAtResourcePath:@"/monkeys.json" usingBlock:^(RKObjectLoader *loader) { loader.objectMapping = [[RKObjectManager sharedManager].mappingProvider objectMappingForClass:[Monkey class]]; }]; } @@ -379,16 +379,16 @@ typedef enum { For example: - - (BOOL)changePassword:(NSString*)newPassword error:(NSError**)error { + - (BOOL)changePassword:(NSString *)newPassword error:(NSError **)error { if ([self validatePassword:newPassword error:error]) { self.password = newPassword; - [[RKObjectManager sharedManager] sendObject:self toResourcePath:@"/some/path" usingBlock:^(RKObjectLoader* loader) { + [[RKObjectManager sharedManager] sendObject:self toResourcePath:@"/some/path" usingBlock:^(RKObjectLoader *loader) { loader.delegate = self; loader.method = RKRequestMethodPOST; loader.serializationMIMEType = RKMIMETypeJSON; // We want to send this request as JSON loader.targetObject = nil; // Map the results back onto a new object instead of self // Set up a custom serialization mapping to handle this request - loader.serializationMapping = [RKObjectMapping serializationMappingUsingBlock:^(RKObjectMapping* mapping) { + loader.serializationMapping = [RKObjectMapping serializationMappingUsingBlock:^(RKObjectMapping *mapping) { [mapping mapAttributes:@"password", nil]; }]; }]; @@ -434,8 +434,8 @@ typedef enum { + (RKObjectManager *)objectManagerWithBaseURLString:(NSString *)baseURLString; + (RKObjectManager *)objectManagerWithBaseURL:(NSURL *)baseURL; -- (void)loadObjectsAtResourcePath:(NSString*)resourcePath objectMapping:(RKObjectMapping*)objectMapping delegate:(id)delegate DEPRECATED_ATTRIBUTE; -- (RKObjectLoader *)objectLoaderWithResourcePath:(NSString*)resourcePath delegate:(id)delegate DEPRECATED_ATTRIBUTE; +- (void)loadObjectsAtResourcePath:(NSString *)resourcePath objectMapping:(RKObjectMapping *)objectMapping delegate:(id)delegate DEPRECATED_ATTRIBUTE; +- (RKObjectLoader *)objectLoaderWithResourcePath:(NSString *)resourcePath delegate:(id)delegate DEPRECATED_ATTRIBUTE; - (RKObjectLoader *)objectLoaderForObject:(id)object method:(RKRequestMethod)method delegate:(id)delegate DEPRECATED_ATTRIBUTE; /* @@ -444,7 +444,7 @@ typedef enum { The mapResponseWith: family of methods have been deprecated by the support for object mapping selection using resourcePath's */ -- (RKObjectLoader*)objectLoaderForObject:(id)object method:(RKRequestMethod)method delegate:(id)delegate; +- (RKObjectLoader *)objectLoaderForObject:(id)object method:(RKRequestMethod)method delegate:(id)delegate; - (RKObjectLoader *)objectLoaderForObject:(id)object method:(RKRequestMethod)method delegate:(id)delegate; - (void)getObject:(id)object mapResponseWith:(RKObjectMapping *)objectMapping delegate:(id)delegate DEPRECATED_ATTRIBUTE; - (void)postObject:(id)object mapResponseWith:(RKObjectMapping *)objectMapping delegate:(id)delegate DEPRECATED_ATTRIBUTE; diff --git a/Code/ObjectMapping/RKObjectManager.m b/Code/ObjectMapping/RKObjectManager.m index 846ffb3318..6860bb36bb 100644 --- a/Code/ObjectMapping/RKObjectManager.m +++ b/Code/ObjectMapping/RKObjectManager.m @@ -23,10 +23,9 @@ #import "RKManagedObjectStore.h" #import "RKManagedObjectLoader.h" #import "Support.h" -#import "RKErrorMessage.h" -NSString* const RKObjectManagerDidBecomeOfflineNotification = @"RKDidEnterOfflineModeNotification"; -NSString* const RKObjectManagerDidBecomeOnlineNotification = @"RKDidEnterOnlineModeNotification"; +NSString * const RKObjectManagerDidBecomeOfflineNotification = @"RKDidEnterOfflineModeNotification"; +NSString * const RKObjectManagerDidBecomeOnlineNotification = @"RKDidEnterOnlineModeNotification"; ////////////////////////////////// // Shared Instances @@ -50,7 +49,8 @@ @implementation RKObjectManager @synthesize networkStatus = _networkStatus; @synthesize mappingQueue = _mappingQueue; -+ (dispatch_queue_t)defaultMappingQueue { ++ (dispatch_queue_t)defaultMappingQueue +{ if (! defaultMappingQueue) { defaultMappingQueue = dispatch_queue_create("org.restkit.ObjectMapping", DISPATCH_QUEUE_SERIAL); } @@ -58,7 +58,8 @@ + (dispatch_queue_t)defaultMappingQueue { return defaultMappingQueue; } -+ (void)setDefaultMappingQueue:(dispatch_queue_t)newDefaultMappingQueue { ++ (void)setDefaultMappingQueue:(dispatch_queue_t)newDefaultMappingQueue +{ if (defaultMappingQueue) { dispatch_release(defaultMappingQueue); defaultMappingQueue = nil; @@ -70,7 +71,8 @@ + (void)setDefaultMappingQueue:(dispatch_queue_t)newDefaultMappingQueue { } } -- (id)init { +- (id)init +{ self = [super init]; if (self) { _mappingProvider = [RKObjectMappingProvider new]; @@ -80,12 +82,6 @@ - (id)init { self.serializationMIMEType = RKMIMETypeFormURLEncoded; self.mappingQueue = [RKObjectManager defaultMappingQueue]; - // Setup default error message mappings - RKObjectMapping *errorMapping = [RKObjectMapping mappingForClass:[RKErrorMessage class]]; - errorMapping.rootKeyPath = @"errors"; - [errorMapping mapKeyPath:@"" toAttribute:@"errorMessage"]; - _mappingProvider.errorMapping = errorMapping; - [self addObserver:self forKeyPath:@"client.reachabilityObserver" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew | NSKeyValueObservingOptionInitial @@ -100,7 +96,8 @@ - (id)init { return self; } -- (id)initWithBaseURL:(RKURL *)baseURL { +- (id)initWithBaseURL:(RKURL *)baseURL +{ self = [self init]; if (self) { self.client = [RKClient clientWithBaseURL:baseURL]; @@ -110,26 +107,31 @@ - (id)initWithBaseURL:(RKURL *)baseURL { return self; } -+ (RKObjectManager *)sharedManager { ++ (RKObjectManager *)sharedManager +{ return sharedManager; } -+ (void)setSharedManager:(RKObjectManager *)manager { ++ (void)setSharedManager:(RKObjectManager *)manager +{ [manager retain]; [sharedManager release]; sharedManager = manager; } -+ (RKObjectManager *)managerWithBaseURLString:(NSString *)baseURLString { ++ (RKObjectManager *)managerWithBaseURLString:(NSString *)baseURLString +{ return [self managerWithBaseURL:[RKURL URLWithString:baseURLString]]; } -+ (RKObjectManager *)managerWithBaseURL:(NSURL *)baseURL { ++ (RKObjectManager *)managerWithBaseURL:(NSURL *)baseURL +{ RKObjectManager *manager = [[[self alloc] initWithBaseURL:baseURL] autorelease]; return manager; } -- (void)dealloc { +- (void)dealloc +{ [self removeObserver:self forKeyPath:@"client.reachabilityObserver"]; [[NSNotificationCenter defaultCenter] removeObserver:self]; @@ -146,11 +148,13 @@ - (void)dealloc { [super dealloc]; } -- (BOOL)isOnline { +- (BOOL)isOnline +{ return (_networkStatus == RKObjectManagerNetworkStatusOnline); } -- (BOOL)isOffline { +- (BOOL)isOffline +{ return (_networkStatus == RKObjectManagerNetworkStatusOffline); } @@ -161,7 +165,8 @@ - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(N } } -- (void)reachabilityObserverDidChange:(NSDictionary *)change { +- (void)reachabilityObserverDidChange:(NSDictionary *)change +{ RKReachabilityObserver *oldReachabilityObserver = [change objectForKey:NSKeyValueChangeOldKey]; RKReachabilityObserver *newReachabilityObserver = [change objectForKey:NSKeyValueChangeNewKey]; @@ -188,7 +193,8 @@ - (void)reachabilityObserverDidChange:(NSDictionary *)change { } } -- (void)reachabilityChanged:(NSNotification *)notification { +- (void)reachabilityChanged:(NSNotification *)notification +{ BOOL isHostReachable = [self.client.reachabilityObserver isNetworkReachable]; _networkStatus = isHostReachable ? RKObjectManagerNetworkStatusOnline : RKObjectManagerNetworkStatusOffline; @@ -200,18 +206,21 @@ - (void)reachabilityChanged:(NSNotification *)notification { } } -- (void)setAcceptMIMEType:(NSString *)MIMEType { +- (void)setAcceptMIMEType:(NSString *)MIMEType +{ [_client setValue:MIMEType forHTTPHeaderField:@"Accept"]; } -- (NSString *)acceptMIMEType { +- (NSString *)acceptMIMEType +{ return [self.client.HTTPHeaders valueForKey:@"Accept"]; } ///////////////////////////////////////////////////////////// #pragma mark - Object Collection Loaders -- (Class)objectLoaderClass { +- (Class)objectLoaderClass +{ Class managedObjectLoaderClass = NSClassFromString(@"RKManagedObjectLoader"); if (self.objectStore && managedObjectLoaderClass) { return managedObjectLoaderClass; @@ -220,12 +229,14 @@ - (Class)objectLoaderClass { return [RKObjectLoader class]; } -- (id)loaderWithResourcePath:(NSString *)resourcePath { +- (id)loaderWithResourcePath:(NSString *)resourcePath +{ RKURL *URL = [self.baseURL URLByAppendingResourcePath:resourcePath]; return [self loaderWithURL:URL]; } -- (id)loaderWithURL:(RKURL *)URL { +- (id)loaderWithURL:(RKURL *)URL +{ RKObjectLoader *loader = [[self objectLoaderClass] loaderWithURL:URL mappingProvider:self.mappingProvider]; loader.configurationDelegate = self; if ([loader isKindOfClass:[RKManagedObjectLoader class]]) { @@ -236,11 +247,13 @@ - (id)loaderWithURL:(RKURL *)URL { return loader; } -- (NSURL *)baseURL { +- (NSURL *)baseURL +{ return self.client.baseURL; } -- (RKObjectPaginator *)paginatorWithResourcePathPattern:(NSString *)resourcePathPattern { +- (RKObjectPaginator *)paginatorWithResourcePathPattern:(NSString *)resourcePathPattern +{ RKURL *patternURL = [[self baseURL] URLByAppendingResourcePath:resourcePathPattern]; RKObjectPaginator *paginator = [RKObjectPaginator paginatorWithPatternURL:patternURL mappingProvider:self.mappingProvider]; @@ -248,8 +261,9 @@ - (RKObjectPaginator *)paginatorWithResourcePathPattern:(NSString *)resourcePath return paginator; } -- (id)loaderForObject:(id)object method:(RKRequestMethod)method { - NSString* resourcePath = (method == RKRequestMethodInvalid) ? nil : [self.router resourcePathForObject:object method:method]; +- (id)loaderForObject:(id)object method:(RKRequestMethod)method +{ + NSString *resourcePath = (method == RKRequestMethodInvalid) ? nil : [self.router resourcePathForObject:object method:method]; RKObjectLoader *loader = [self loaderWithResourcePath:resourcePath]; loader.method = method; loader.sourceObject = object; @@ -266,7 +280,8 @@ - (id)loaderForObject:(id)object method:(RKRequestMethod)method { return loader; } -- (void)loadObjectsAtResourcePath:(NSString *)resourcePath delegate:(id)delegate { +- (void)loadObjectsAtResourcePath:(NSString *)resourcePath delegate:(id)delegate +{ RKObjectLoader *loader = [self loaderWithResourcePath:resourcePath]; loader.delegate = delegate; loader.method = RKRequestMethodGET; @@ -277,25 +292,29 @@ - (void)loadObjectsAtResourcePath:(NSString *)resourcePath delegate:(id)object delegate:(id)delegate { +- (void)getObject:(id)object delegate:(id)delegate +{ RKObjectLoader *loader = [self loaderForObject:object method:RKRequestMethodGET]; loader.delegate = delegate; [loader send]; } -- (void)postObject:(id)object delegate:(id)delegate { +- (void)postObject:(id)object delegate:(id)delegate +{ RKObjectLoader *loader = [self loaderForObject:object method:RKRequestMethodPOST]; loader.delegate = delegate; [loader send]; } -- (void)putObject:(id)object delegate:(id)delegate { +- (void)putObject:(id)object delegate:(id)delegate +{ RKObjectLoader *loader = [self loaderForObject:object method:RKRequestMethodPUT]; loader.delegate = delegate; [loader send]; } -- (void)deleteObject:(id)object delegate:(id)delegate { +- (void)deleteObject:(id)object delegate:(id)delegate +{ RKObjectLoader *loader = [self loaderForObject:object method:RKRequestMethodDELETE]; loader.delegate = delegate; [loader send]; @@ -305,8 +324,9 @@ - (void)deleteObject:(id)object delegate:(id)d #pragma mark - Block Configured Object Loaders -- (void)loadObjectsAtResourcePath:(NSString*)resourcePath usingBlock:(void(^)(RKObjectLoader *))block { - RKObjectLoader* loader = [self loaderWithResourcePath:resourcePath]; +- (void)loadObjectsAtResourcePath:(NSString *)resourcePath usingBlock:(void(^)(RKObjectLoader *))block +{ + RKObjectLoader *loader = [self loaderWithResourcePath:resourcePath]; loader.method = RKRequestMethodGET; // Yield to the block for setup @@ -315,7 +335,8 @@ - (void)loadObjectsAtResourcePath:(NSString*)resourcePath usingBlock:(void(^)(RK [loader send]; } -- (void)sendObject:(id)object toResourcePath:(NSString *)resourcePath usingBlock:(void(^)(RKObjectLoader *))block { +- (void)sendObject:(id)object toResourcePath:(NSString *)resourcePath usingBlock:(void(^)(RKObjectLoader *))block +{ RKObjectLoader *loader = [self loaderForObject:object method:RKRequestMethodInvalid]; loader.URL = [self.baseURL URLByAppendingResourcePath:resourcePath]; // Yield to the block for setup @@ -324,7 +345,8 @@ - (void)sendObject:(id)object toResourcePath:(NSString *)resourcePath [loader send]; } -- (void)sendObject:(id)object method:(RKRequestMethod)method usingBlock:(void(^)(RKObjectLoader *))block { +- (void)sendObject:(id)object method:(RKRequestMethod)method usingBlock:(void(^)(RKObjectLoader *))block +{ NSString *resourcePath = [self.router resourcePathForObject:object method:method]; [self sendObject:object toResourcePath:resourcePath usingBlock:^(RKObjectLoader *loader) { loader.method = method; @@ -332,19 +354,23 @@ - (void)sendObject:(id)object method:(RKRequestMethod)method usingBloc }]; } -- (void)getObject:(id)object usingBlock:(void(^)(RKObjectLoader *))block { +- (void)getObject:(id)object usingBlock:(void(^)(RKObjectLoader *))block +{ [self sendObject:object method:RKRequestMethodGET usingBlock:block]; } -- (void)postObject:(id)object usingBlock:(void(^)(RKObjectLoader *))block { +- (void)postObject:(id)object usingBlock:(void(^)(RKObjectLoader *))block +{ [self sendObject:object method:RKRequestMethodPOST usingBlock:block]; } -- (void)putObject:(id)object usingBlock:(void(^)(RKObjectLoader *))block { +- (void)putObject:(id)object usingBlock:(void(^)(RKObjectLoader *))block +{ [self sendObject:object method:RKRequestMethodPUT usingBlock:block]; } -- (void)deleteObject:(id)object usingBlock:(void(^)(RKObjectLoader *))block { +- (void)deleteObject:(id)object usingBlock:(void(^)(RKObjectLoader *))block +{ [self sendObject:object method:RKRequestMethodDELETE usingBlock:block]; } @@ -352,43 +378,50 @@ - (void)deleteObject:(id)object usingBlock:(void(^)(RKObjectLoader *)) #pragma mark - Object Instance Loaders for Non-nested JSON -- (void)getObject:(id)object mapResponseWith:(RKObjectMapping *)objectMapping delegate:(id)delegate { +- (void)getObject:(id)object mapResponseWith:(RKObjectMapping *)objectMapping delegate:(id)delegate +{ [self sendObject:object method:RKRequestMethodGET usingBlock:^(RKObjectLoader *loader) { loader.delegate = delegate; loader.objectMapping = objectMapping; }]; } -- (void)postObject:(id)object mapResponseWith:(RKObjectMapping *)objectMapping delegate:(id)delegate { +- (void)postObject:(id)object mapResponseWith:(RKObjectMapping *)objectMapping delegate:(id)delegate +{ [self sendObject:object method:RKRequestMethodPOST usingBlock:^(RKObjectLoader *loader) { loader.delegate = delegate; loader.objectMapping = objectMapping; }]; } -- (void)putObject:(id)object mapResponseWith:(RKObjectMapping *)objectMapping delegate:(id)delegate { +- (void)putObject:(id)object mapResponseWith:(RKObjectMapping *)objectMapping delegate:(id)delegate +{ [self sendObject:object method:RKRequestMethodPUT usingBlock:^(RKObjectLoader *loader) { loader.delegate = delegate; loader.objectMapping = objectMapping; }]; } -- (void)deleteObject:(id)object mapResponseWith:(RKObjectMapping *)objectMapping delegate:(id)delegate { +- (void)deleteObject:(id)object mapResponseWith:(RKObjectMapping *)objectMapping delegate:(id)delegate +{ [self sendObject:object method:RKRequestMethodDELETE usingBlock:^(RKObjectLoader *loader) { loader.delegate = delegate; loader.objectMapping = objectMapping; }]; } -- (RKRequestCache *)requestCache { +- (RKRequestCache *)requestCache +{ return self.client.requestCache; } -- (RKRequestQueue *)requestQueue { +- (RKRequestQueue *)requestQueue +{ return self.client.requestQueue; } -- (void)setMappingQueue:(dispatch_queue_t)newMappingQueue { +- (void)setMappingQueue:(dispatch_queue_t)newMappingQueue +{ if (_mappingQueue) { dispatch_release(_mappingQueue); _mappingQueue = nil; @@ -402,39 +435,46 @@ - (void)setMappingQueue:(dispatch_queue_t)newMappingQueue { #pragma mark - RKConfigrationDelegate -- (void)configureRequest:(RKRequest *)request { +- (void)configureRequest:(RKRequest *)request +{ [self.client configureRequest:request]; } -- (void)configureObjectLoader:(RKObjectLoader *)objectLoader { +- (void)configureObjectLoader:(RKObjectLoader *)objectLoader +{ objectLoader.serializationMIMEType = self.serializationMIMEType; [self configureRequest:objectLoader]; } #pragma mark - Deprecations -+ (RKObjectManager *)objectManagerWithBaseURLString:(NSString *)baseURLString { ++ (RKObjectManager *)objectManagerWithBaseURLString:(NSString *)baseURLString +{ return [self managerWithBaseURLString:baseURLString]; } -+ (RKObjectManager *)objectManagerWithBaseURL:(NSURL *)baseURL { ++ (RKObjectManager *)objectManagerWithBaseURL:(NSURL *)baseURL +{ return [self managerWithBaseURL:baseURL]; } -- (RKObjectLoader *)objectLoaderWithResourcePath:(NSString *)resourcePath delegate:(id)delegate { - RKObjectLoader* loader = [self loaderWithResourcePath:resourcePath]; +- (RKObjectLoader *)objectLoaderWithResourcePath:(NSString *)resourcePath delegate:(id)delegate +{ + RKObjectLoader *loader = [self loaderWithResourcePath:resourcePath]; loader.delegate = delegate; return loader; } -- (RKObjectLoader*)objectLoaderForObject:(id)object method:(RKRequestMethod)method delegate:(id)delegate { +- (RKObjectLoader *)objectLoaderForObject:(id)object method:(RKRequestMethod)method delegate:(id)delegate +{ RKObjectLoader *loader = [self loaderForObject:object method:method]; loader.delegate = delegate; return loader; } -- (void)loadObjectsAtResourcePath:(NSString *)resourcePath objectMapping:(RKObjectMapping *)objectMapping delegate:(id)delegate { +- (void)loadObjectsAtResourcePath:(NSString *)resourcePath objectMapping:(RKObjectMapping *)objectMapping delegate:(id)delegate +{ RKObjectLoader *loader = [self loaderWithResourcePath:resourcePath]; loader.delegate = delegate; loader.method = RKRequestMethodGET; diff --git a/Code/ObjectMapping/RKObjectMapper.h b/Code/ObjectMapping/RKObjectMapper.h index d7fc361c6c..01173bee54 100644 --- a/Code/ObjectMapping/RKObjectMapper.h +++ b/Code/ObjectMapping/RKObjectMapper.h @@ -32,15 +32,15 @@ @optional -- (void)objectMapperWillBeginMapping:(RKObjectMapper*)objectMapper; -- (void)objectMapperDidFinishMapping:(RKObjectMapper*)objectMapper; -- (void)objectMapper:(RKObjectMapper*)objectMapper didAddError:(NSError*)error; -- (void)objectMapper:(RKObjectMapper*)objectMapper didFindMappableObject:(id)object atKeyPath:(NSString*)keyPath withMapping:(RKObjectMappingDefinition *)mapping; -- (void)objectMapper:(RKObjectMapper*)objectMapper didNotFindMappableObjectAtKeyPath:(NSString*)keyPath; +- (void)objectMapperWillBeginMapping:(RKObjectMapper *)objectMapper; +- (void)objectMapperDidFinishMapping:(RKObjectMapper *)objectMapper; +- (void)objectMapper:(RKObjectMapper *)objectMapper didAddError:(NSError *)error; +- (void)objectMapper:(RKObjectMapper *)objectMapper didFindMappableObject:(id)object atKeyPath:(NSString *)keyPath withMapping:(RKObjectMappingDefinition *)mapping; +- (void)objectMapper:(RKObjectMapper *)objectMapper didNotFindMappableObjectAtKeyPath:(NSString *)keyPath; -- (void)objectMapper:(RKObjectMapper*)objectMapper willMapFromObject:(id)sourceObject toObject:(id)destinationObject atKeyPath:(NSString*)keyPath usingMapping:(RKObjectMappingDefinition *)objectMapping; -- (void)objectMapper:(RKObjectMapper*)objectMapper didMapFromObject:(id)sourceObject toObject:(id)destinationObject atKeyPath:(NSString*)keyPath usingMapping:(RKObjectMappingDefinition *)objectMapping; -- (void)objectMapper:(RKObjectMapper*)objectMapper didFailMappingFromObject:(id)sourceObject toObject:(id)destinationObject withError:(NSError*)error atKeyPath:(NSString*)keyPath usingMapping:(RKObjectMappingDefinition *)objectMapping; +- (void)objectMapper:(RKObjectMapper *)objectMapper willMapFromObject:(id)sourceObject toObject:(id)destinationObject atKeyPath:(NSString *)keyPath usingMapping:(RKObjectMappingDefinition *)objectMapping; +- (void)objectMapper:(RKObjectMapper *)objectMapper didMapFromObject:(id)sourceObject toObject:(id)destinationObject atKeyPath:(NSString *)keyPath usingMapping:(RKObjectMappingDefinition *)objectMapping; +- (void)objectMapper:(RKObjectMapper *)objectMapper didFailMappingFromObject:(id)sourceObject toObject:(id)destinationObject withError:(NSError *)error atKeyPath:(NSString *)keyPath usingMapping:(RKObjectMappingDefinition *)objectMapping; @end /** @@ -49,21 +49,21 @@ @interface RKObjectMapper : NSObject { @protected RKMappingOperationQueue *operationQueue; - NSMutableArray* errors; + NSMutableArray *errors; } @property (nonatomic, readonly) id sourceObject; @property (nonatomic, assign) id targetObject; -@property (nonatomic, readonly) RKObjectMappingProvider* mappingProvider; +@property (nonatomic, readonly) RKObjectMappingProvider *mappingProvider; @property (nonatomic, assign) RKObjectMappingProviderContext context; @property (nonatomic, assign) id delegate; -@property (nonatomic, readonly) NSArray* errors; +@property (nonatomic, readonly) NSArray *errors; -+ (id)mapperWithObject:(id)object mappingProvider:(RKObjectMappingProvider*)mappingProvider; -- (id)initWithObject:(id)object mappingProvider:(RKObjectMappingProvider*)mappingProvider; ++ (id)mapperWithObject:(id)object mappingProvider:(RKObjectMappingProvider *)mappingProvider; +- (id)initWithObject:(id)object mappingProvider:(RKObjectMappingProvider *)mappingProvider; // Primary entry point for the mapper. Examines the type of object and processes it appropriately... -- (RKObjectMappingResult*)performMapping; +- (RKObjectMappingResult *)performMapping; - (NSUInteger)errorCount; @end diff --git a/Code/ObjectMapping/RKObjectMapper.m b/Code/ObjectMapping/RKObjectMapper.m index cc97b1b92d..582cb9511c 100644 --- a/Code/ObjectMapping/RKObjectMapper.m +++ b/Code/ObjectMapping/RKObjectMapper.m @@ -36,11 +36,13 @@ @implementation RKObjectMapper @synthesize errors; @synthesize context; -+ (id)mapperWithObject:(id)object mappingProvider:(RKObjectMappingProvider *)theMappingProvider { ++ (id)mapperWithObject:(id)object mappingProvider:(RKObjectMappingProvider *)theMappingProvider +{ return [[[self alloc] initWithObject:object mappingProvider:theMappingProvider] autorelease]; } -- (id)initWithObject:(id)object mappingProvider:(RKObjectMappingProvider *)theMappingProvider { +- (id)initWithObject:(id)object mappingProvider:(RKObjectMappingProvider *)theMappingProvider +{ self = [super init]; if (self) { sourceObject = [object retain]; @@ -53,7 +55,8 @@ - (id)initWithObject:(id)object mappingProvider:(RKObjectMappingProvider *)theMa return self; } -- (void)dealloc { +- (void)dealloc +{ [sourceObject release]; [errors release]; [operationQueue release]; @@ -62,15 +65,18 @@ - (void)dealloc { #pragma mark - Errors -- (NSArray *)errors { +- (NSArray *)errors +{ return [NSArray arrayWithArray:errors]; } -- (NSUInteger)errorCount { +- (NSUInteger)errorCount +{ return [self.errors count]; } -- (void)addError:(NSError *)error { +- (void)addError:(NSError *)error +{ NSAssert(error, @"Cannot add a nil error"); [errors addObject:error]; @@ -81,22 +87,25 @@ - (void)addError:(NSError *)error { RKLogWarning(@"Adding mapping error: %@", [error localizedDescription]); } -- (void)addErrorWithCode:(RKObjectMapperErrorCode)errorCode message:(NSString *)errorMessage keyPath:(NSString *)keyPath userInfo:(NSDictionary *)otherInfo { +- (void)addErrorWithCode:(RKObjectMapperErrorCode)errorCode message:(NSString *)errorMessage keyPath:(NSString *)keyPath userInfo:(NSDictionary *)otherInfo +{ NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithObjectsAndKeys: errorMessage, NSLocalizedDescriptionKey, - @"RKObjectMapperKeyPath", keyPath ? keyPath : (NSString *) [NSNull null], + @"RKObjectMapperKeyPath", keyPath ? keyPath : (NSString *)[NSNull null], nil]; [userInfo addEntriesFromDictionary:otherInfo]; - NSError* error = [NSError errorWithDomain:RKErrorDomain code:errorCode userInfo:userInfo]; + NSError *error = [NSError errorWithDomain:RKErrorDomain code:errorCode userInfo:userInfo]; [self addError:error]; } -- (void)addErrorForUnmappableKeyPath:(NSString *)keyPath { +- (void)addErrorForUnmappableKeyPath:(NSString *)keyPath +{ NSString *errorMessage = [NSString stringWithFormat:@"Could not find an object mapping for keyPath: '%@'", keyPath]; [self addErrorWithCode:RKObjectMapperErrorObjectMappingNotFound message:errorMessage keyPath:keyPath userInfo:nil]; } -- (BOOL)isNullCollection:(id)object { +- (BOOL)isNullCollection:(id)object +{ // The purpose of this method is to guard against the case where we perform valueForKeyPath: on an array // and it returns NSNull for each element in the array. @@ -118,7 +127,8 @@ - (BOOL)isNullCollection:(id)object { #pragma mark - Mapping Primitives -- (id)mapObject:(id)mappableObject atKeyPath:(NSString *)keyPath usingMapping:(RKObjectMappingDefinition *)mapping { +- (id)mapObject:(id)mappableObject atKeyPath:(NSString *)keyPath usingMapping:(RKObjectMappingDefinition *)mapping +{ NSAssert([mappableObject respondsToSelector:@selector(setValue:forKeyPath:)], @"Expected self.object to be KVC compliant"); id destinationObject = nil; @@ -157,7 +167,8 @@ - (id)mapObject:(id)mappableObject atKeyPath:(NSString *)keyPath usingMapping:(R return nil; } -- (NSArray *)mapCollection:(NSArray *)mappableObjects atKeyPath:(NSString *)keyPath usingMapping:(RKObjectMappingDefinition *)mapping { +- (NSArray *)mapCollection:(NSArray *)mappableObjects atKeyPath:(NSString *)keyPath usingMapping:(RKObjectMappingDefinition *)mapping +{ NSAssert(mappableObjects != nil, @"Cannot map without an collection of mappable objects"); NSAssert(mapping != nil, @"Cannot map without a mapping to consult"); @@ -202,7 +213,8 @@ - (NSArray *)mapCollection:(NSArray *)mappableObjects atKeyPath:(NSString *)keyP } // The workhorse of this entire process. Emits object loading operations -- (BOOL)mapFromObject:(id)mappableObject toObject:(id)destinationObject atKeyPath:(NSString *)keyPath usingMapping:(RKObjectMappingDefinition *)mapping { +- (BOOL)mapFromObject:(id)mappableObject toObject:(id)destinationObject atKeyPath:(NSString *)keyPath usingMapping:(RKObjectMappingDefinition *)mapping +{ NSAssert(destinationObject != nil, @"Cannot map without a target object to assign the results to"); NSAssert(mappableObject != nil, @"Cannot map without a collection of attributes"); NSAssert(mapping != nil, @"Cannot map without an mapping"); @@ -234,7 +246,8 @@ - (BOOL)mapFromObject:(id)mappableObject toObject:(id)destinationObject atKeyPat return success; } -- (id)objectWithMapping:(RKObjectMappingDefinition *)mapping andData:(id)mappableData { +- (id)objectWithMapping:(RKObjectMappingDefinition *)mapping andData:(id)mappableData +{ NSAssert([mapping isKindOfClass:[RKObjectMappingDefinition class]], @"Expected an RKObjectMappingDefinition object"); RKObjectMapping *objectMapping = nil; if ([mapping isKindOfClass:[RKDynamicObjectMapping class]]) { @@ -255,7 +268,8 @@ - (id)objectWithMapping:(RKObjectMappingDefinition *)mapping andData:(id)mappabl return nil; } -- (id)performMappingForObject:(id)mappableValue atKeyPath:(NSString *)keyPath usingMapping:(RKObjectMappingDefinition *)mapping { +- (id)performMappingForObject:(id)mappableValue atKeyPath:(NSString *)keyPath usingMapping:(RKObjectMappingDefinition *)mapping +{ id mappingResult; if (mapping.forceCollectionMapping || [mappableValue isKindOfClass:[NSArray class]] || [mappableValue isKindOfClass:[NSSet class]]) { RKLogDebug(@"Found mappable collection at keyPath '%@': %@", keyPath, mappableValue); @@ -268,7 +282,8 @@ - (id)performMappingForObject:(id)mappableValue atKeyPath:(NSString *)keyPath us return mappingResult; } -- (NSMutableDictionary *)performKeyPathMappingUsingMappingDictionary:(NSDictionary *)mappingsByKeyPath { +- (NSMutableDictionary *)performKeyPathMappingUsingMappingDictionary:(NSDictionary *)mappingsByKeyPath +{ BOOL foundMappable = NO; NSMutableDictionary *results = [NSMutableDictionary dictionary]; for (NSString *keyPath in mappingsByKeyPath) { @@ -296,7 +311,7 @@ - (NSMutableDictionary *)performKeyPathMappingUsingMappingDictionary:(NSDictiona // Found something to map foundMappable = YES; - RKObjectMappingDefinition * mapping = [mappingsByKeyPath objectForKey:keyPath]; + RKObjectMappingDefinition *mapping = [mappingsByKeyPath objectForKey:keyPath]; if ([self.delegate respondsToSelector:@selector(objectMapper:didFindMappableObject:atKeyPath:withMapping:)]) { [self.delegate objectMapper:self didFindMappableObject:mappableValue atKeyPath:keyPath withMapping:mapping]; } @@ -313,7 +328,8 @@ - (NSMutableDictionary *)performKeyPathMappingUsingMappingDictionary:(NSDictiona } // Primary entry point for the mapper. -- (RKObjectMappingResult *)performMapping { +- (RKObjectMappingResult *)performMapping +{ NSAssert(self.sourceObject != nil, @"Cannot perform object mapping without a source object to map from"); NSAssert(self.mappingProvider != nil, @"Cannot perform object mapping without an object mapping provider"); @@ -335,7 +351,7 @@ - (RKObjectMappingResult *)performMapping { } else if ([mappingsForContext isKindOfClass:[RKObjectMappingDefinition class]]) { id mappableData = self.sourceObject; if ([mappingsForContext rootKeyPath] != nil) { - NSString* rootKeyPath = [mappingsForContext rootKeyPath]; + NSString *rootKeyPath = [mappingsForContext rootKeyPath]; mappableData = [self.sourceObject valueForKeyPath:rootKeyPath]; RKLogDebug(@"Selected object mapping has rootKeyPath. Apply valueForKeyPath to mappable data: %@", rootKeyPath); } diff --git a/Code/ObjectMapping/RKObjectMapper_Private.h b/Code/ObjectMapping/RKObjectMapper_Private.h index d78f2f86f4..c5e3044697 100644 --- a/Code/ObjectMapping/RKObjectMapper_Private.h +++ b/Code/ObjectMapping/RKObjectMapper_Private.h @@ -21,7 +21,7 @@ @interface RKObjectMapper (Private) - (id)mapObject:(id)mappableObject atKeyPath:(NSString *)keyPath usingMapping:(RKObjectMappingDefinition *)mapping; -- (NSArray*)mapCollection:(NSArray*)mappableObjects atKeyPath:(NSString*)keyPath usingMapping:(RKObjectMappingDefinition *)mapping; +- (NSArray *)mapCollection:(NSArray *)mappableObjects atKeyPath:(NSString *)keyPath usingMapping:(RKObjectMappingDefinition *)mapping; - (BOOL)mapFromObject:(id)mappableObject toObject:(id)destinationObject atKeyPath:(NSString *)keyPath usingMapping:(RKObjectMappingDefinition *)mapping; - (id)objectWithMapping:(RKObjectMappingDefinition *)objectMapping andData:(id)mappableData; diff --git a/Code/ObjectMapping/RKObjectMapping.h b/Code/ObjectMapping/RKObjectMapping.h index 7c0f51f557..3073211f58 100644 --- a/Code/ObjectMapping/RKObjectMapping.h +++ b/Code/ObjectMapping/RKObjectMapping.h @@ -45,13 +45,7 @@ relationship. Relationships are processed using an object mapping as well. */ @interface RKObjectMapping : RKObjectMappingDefinition { Class _objectClass; - NSMutableArray* _mappings; - NSString* _rootKeyPath; - BOOL _setDefaultValueForMissingAttributes; - BOOL _setNilForMissingRelationships; - BOOL _performKeyValueValidation; - NSArray *_dateFormatters; - NSFormatter *_preferredDateFormatter; + NSMutableArray *_mappings; } /** @@ -176,8 +170,8 @@ relationship. Relationships are processed using an object mapping as well. For example, consider we have a one-off request that will load a few attributes for our object. Using blocks, this is very succinct: - [[RKObjectManager sharedManager] postObject:self usingBlock:^(RKObjectLoader* loader) { - loader.objectMapping = [RKObjectMapping mappingForClass:[Person class] usingBlock:^(RKObjectMapping* mapping) { + [[RKObjectManager sharedManager] postObject:self usingBlock:^(RKObjectLoader *loader) { + loader.objectMapping = [RKObjectMapping mappingForClass:[Person class] usingBlock:^(RKObjectMapping *mapping) { [mapping mapAttributes:@"email", @"first_name", nil]; }]; }]; @@ -192,11 +186,11 @@ relationship. Relationships are processed using an object mapping as well. For example, consider we have a one-off request within which we want to post a subset of our object data. Using blocks, this is very succinct: - - (BOOL)changePassword:(NSString*)newPassword error:(NSError**)error { + - (BOOL)changePassword:(NSString *)newPassword error:(NSError **)error { if ([self validatePassword:newPassword error:error]) { self.password = newPassword; - [[RKObjectManager sharedManager] putObject:self delegate:self block:^(RKObjectLoader* loader) { - loader.serializationMapping = [RKObjectMapping serializationMappingUsingBlock:^(RKObjectMapping* mapping) { + [[RKObjectManager sharedManager] putObject:self delegate:self block:^(RKObjectLoader *loader) { + loader.serializationMapping = [RKObjectMapping serializationMappingUsingBlock:^(RKObjectMapping *mapping) { [mapping mapAttributes:@"password", nil]; }]; }]; @@ -213,14 +207,14 @@ relationship. Relationships are processed using an object mapping as well. @see RKObjectAttributeMapping */ -- (void)addAttributeMapping:(RKObjectAttributeMapping*)mapping; +- (void)addAttributeMapping:(RKObjectAttributeMapping *)mapping; /** Add a configured attribute mapping to this object mapping @see RKObjectRelationshipMapping */ -- (void)addRelationshipMapping:(RKObjectRelationshipMapping*)mapping; +- (void)addRelationshipMapping:(RKObjectRelationshipMapping *)mapping; #pragma mark - Retrieving Mappings @@ -230,7 +224,7 @@ relationship. Relationships are processed using an object mapping as well. @param sourceKeyPath A keyPath within the mappable source object that is mapped to an attribute or relationship in this object mapping. */ -- (id)mappingForKeyPath:(NSString*)sourceKeyPath; +- (id)mappingForKeyPath:(NSString *)sourceKeyPath; /** Returns the attribute or relationship mapping for the given source keyPath. @@ -238,7 +232,7 @@ relationship. Relationships are processed using an object mapping as well. @param sourceKeyPath A keyPath within the mappable source object that is mapped to an attribute or relationship in this object mapping. */ -- (id)mappingForSourceKeyPath:(NSString*)sourceKeyPath; +- (id)mappingForSourceKeyPath:(NSString *)sourceKeyPath; /** Returns the attribute or relationship mapping for the given destination keyPath. @@ -259,7 +253,7 @@ relationship. Relationships are processed using an object mapping as well. @param relationshipKey The name of the relationship we want to retrieve the mapping for */ -- (RKObjectRelationshipMapping*)mappingForRelationship:(NSString*)relationshipKey; +- (RKObjectRelationshipMapping *)mappingForRelationship:(NSString *)relationshipKey; #pragma mark - Attribute & Relationship Mapping @@ -322,14 +316,14 @@ relationship. Relationships are processed using an object mapping as well. To a Person class with corresponding 'cat' relationship property, we could configure the mappings via: - RKObjectMapping* catMapping = [RKObjectMapping mappingForClass:[Cat class]]; + RKObjectMapping *catMapping = [RKObjectMapping mappingForClass:[Cat class]]; [personMapping mapRelationship:@"cat" withObjectMapping:catMapping]; @param relationshipKey A key-value coding key corresponding to a value in the mappable source object and a property on the destination class that have the same name. @param objectOrDynamicMapping An RKObjectMapping or RKObjectDynamic mapping to apply when mapping the relationship */ -- (void)mapRelationship:(NSString*)relationshipKey withMapping:(RKObjectMappingDefinition *)objectOrDynamicMapping; +- (void)mapRelationship:(NSString *)relationshipKey withMapping:(RKObjectMappingDefinition *)objectOrDynamicMapping; /** Syntactic sugar to improve readability when defining a relationship mapping. Implies that the mapping @@ -337,7 +331,7 @@ relationship. Relationships are processed using an object mapping as well. @see mapRelationship:withObjectMapping: */ -- (void)hasMany:(NSString*)keyPath withMapping:(RKObjectMappingDefinition *)objectOrDynamicMapping; +- (void)hasMany:(NSString *)keyPath withMapping:(RKObjectMappingDefinition *)objectOrDynamicMapping; /** Syntactic sugar to improve readability when defining a relationship mapping. Implies that the mapping @@ -345,7 +339,7 @@ relationship. Relationships are processed using an object mapping as well. @see mapRelationship:withObjectMapping: */ -- (void)hasOne:(NSString*)keyPath withMapping:(RKObjectMappingDefinition *)objectOrDynamicMapping; +- (void)hasOne:(NSString *)keyPath withMapping:(RKObjectMappingDefinition *)objectOrDynamicMapping; /** Instantiate and add an RKObjectAttributeMapping instance targeting a keyPath within the mappable @@ -365,7 +359,7 @@ relationship. Relationships are processed using an object mapping as well. @param destinationAttribute The attribute name to assign the mapped value to @see RKObjectAttributeMapping */ -- (void)mapKeyPath:(NSString*)sourceKeyPath toAttribute:(NSString*)destinationAttribute; +- (void)mapKeyPath:(NSString *)sourceKeyPath toAttribute:(NSString *)destinationAttribute; /** Instantiate and add an RKObjectRelationshipMapping instance targeting a keyPath within the mappable @@ -386,7 +380,7 @@ relationship. Relationships are processed using an object mapping as well. @param objectMapping An object mapping to use when processing the nested objects @see RKObjectRelationshipMapping */ -- (void)mapKeyPath:(NSString *)sourceKeyPath toRelationship:(NSString*)destinationRelationship withMapping:(RKObjectMappingDefinition *)objectOrDynamicMapping; +- (void)mapKeyPath:(NSString *)sourceKeyPath toRelationship:(NSString *)destinationRelationship withMapping:(RKObjectMappingDefinition *)objectOrDynamicMapping; /** Instantiate and add an RKObjectRelationshipMapping instance targeting a keyPath within the mappable @@ -401,7 +395,7 @@ relationship. Relationships are processed using an object mapping as well. @see mapKeyPath:toRelationship:withObjectMapping: */ -- (void)mapKeyPath:(NSString *)relationshipKeyPath toRelationship:(NSString*)keyPath withMapping:(RKObjectMappingDefinition *)objectOrDynamicMapping serialize:(BOOL)serialize; +- (void)mapKeyPath:(NSString *)relationshipKeyPath toRelationship:(NSString *)keyPath withMapping:(RKObjectMappingDefinition *)objectOrDynamicMapping serialize:(BOOL)serialize; /** Quickly define a group of attribute mappings using alternating keyPath and attribute names. You must provide @@ -413,7 +407,7 @@ relationship. Relationships are processed using an object mapping as well. @param sourceKeyPath A key-value coding key path to fetch a mappable value from @param ... A nil-terminated sequence of strings alternating between source key paths and destination attributes */ -- (void)mapKeyPathsToAttributes:(NSString*)sourceKeyPath, ... NS_REQUIRES_NIL_TERMINATION; +- (void)mapKeyPathsToAttributes:(NSString *)sourceKeyPath, ... NS_REQUIRES_NIL_TERMINATION; /** @@ -430,7 +424,7 @@ relationship. Relationships are processed using an object mapping as well. We can configure our mappings to handle this in the following form: - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[User class]]; + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[User class]]; mapping.forceCollectionMapping = YES; // RestKit cannot infer this is a collection, so we force it [mapping mapKeyOfNestedDictionaryToAttribute:@"firstName"]; [mapping mapFromKeyPath:@"(firstName).id" toAttribute:"userID"]; @@ -459,14 +453,14 @@ relationship. Relationships are processed using an object mapping as well. @param attributeOrRelationshipMapping The attribute or relationship mapping to remove */ -- (void)removeMapping:(RKObjectAttributeMapping*)attributeOrRelationshipMapping; +- (void)removeMapping:(RKObjectAttributeMapping *)attributeOrRelationshipMapping; /** Remove the attribute or relationship mapping for the specified source keyPath @param sourceKeyPath A key-value coding key path to remove the mappings for */ -- (void)removeMappingForKeyPath:(NSString*)sourceKeyPath; +- (void)removeMappingForKeyPath:(NSString *)sourceKeyPath; #pragma mark - Inverse Mappings @@ -475,7 +469,7 @@ relationship. Relationships are processed using an object mapping as well. quickly generate a corresponding serialization mapping from a configured object mapping. The inverse mapping will have the source and destination keyPaths swapped for all attribute and relationship mappings. */ -- (RKObjectMapping*)inverseMapping; +- (RKObjectMapping *)inverseMapping; /** Returns the default value to be assigned to the specified attribute when it is missing from a @@ -486,7 +480,7 @@ relationship. Relationships are processed using an object mapping as well. @see [RKManagedObjectMapping defaultValueForMissingAttribute:] */ -- (id)defaultValueForMissingAttribute:(NSString*)attributeName; +- (id)defaultValueForMissingAttribute:(NSString *)attributeName; /** Returns an auto-released object that can be used to apply this object mapping @@ -503,7 +497,7 @@ relationship. Relationships are processed using an object mapping as well. @param propertyName The name of the property we would like to retrieve the type of */ -- (Class)classForProperty:(NSString*)propertyName; +- (Class)classForProperty:(NSString *)propertyName; /** Returns an auto-released object that can be used to apply this object mapping @@ -514,9 +508,9 @@ relationship. Relationships are processed using an object mapping as well. - (id)mappableObjectForData:(id)mappableData; // Deprecations -+ (id)mappingForClass:(Class)objectClass withBlock:(void (^)(RKObjectMapping*))block DEPRECATED_ATTRIBUTE; -+ (id)mappingForClass:(Class)objectClass block:(void (^)(RKObjectMapping*))block DEPRECATED_ATTRIBUTE; -+ (id)serializationMappingWithBlock:(void (^)(RKObjectMapping*))block DEPRECATED_ATTRIBUTE; ++ (id)mappingForClass:(Class)objectClass withBlock:(void (^)(RKObjectMapping *))block DEPRECATED_ATTRIBUTE; ++ (id)mappingForClass:(Class)objectClass block:(void (^)(RKObjectMapping *))block DEPRECATED_ATTRIBUTE; ++ (id)serializationMappingWithBlock:(void (^)(RKObjectMapping *))block DEPRECATED_ATTRIBUTE; @end diff --git a/Code/ObjectMapping/RKObjectMapping.m b/Code/ObjectMapping/RKObjectMapping.m index 373151f5c6..8314ddf16d 100644 --- a/Code/ObjectMapping/RKObjectMapping.m +++ b/Code/ObjectMapping/RKObjectMapping.m @@ -25,7 +25,7 @@ #import "RKISO8601DateFormatter.h" // Constants -NSString* const RKObjectMappingNestingAttributeKeyName = @""; +NSString * const RKObjectMappingNestingAttributeKeyName = @""; @implementation RKObjectMapping @@ -39,52 +39,61 @@ @implementation RKObjectMapping @synthesize performKeyValueValidation = _performKeyValueValidation; @synthesize ignoreUnknownKeyPaths = _ignoreUnknownKeyPaths; -+ (id)mappingForClass:(Class)objectClass { - RKObjectMapping* mapping = [self new]; ++ (id)mappingForClass:(Class)objectClass +{ + RKObjectMapping *mapping = [self new]; mapping.objectClass = objectClass; return [mapping autorelease]; } -+ (id)mappingForClassWithName:(NSString *)objectClassName { ++ (id)mappingForClassWithName:(NSString *)objectClassName +{ return [self mappingForClass:NSClassFromString(objectClassName)]; } -+ (id)serializationMapping { ++ (id)serializationMapping +{ return [self mappingForClass:[NSMutableDictionary class]]; } #if NS_BLOCKS_AVAILABLE -+ (id)mappingForClass:(Class)objectClass usingBlock:(void (^)(RKObjectMapping*))block { - RKObjectMapping* mapping = [self mappingForClass:objectClass]; ++ (id)mappingForClass:(Class)objectClass usingBlock:(void (^)(RKObjectMapping *))block +{ + RKObjectMapping *mapping = [self mappingForClass:objectClass]; block(mapping); return mapping; } -+ (id)serializationMappingUsingBlock:(void (^)(RKObjectMapping*))block { - RKObjectMapping* mapping = [self serializationMapping]; ++ (id)serializationMappingUsingBlock:(void (^)(RKObjectMapping *))block +{ + RKObjectMapping *mapping = [self serializationMapping]; block(mapping); return mapping; } // Deprecated... Move to category or bottom... -+ (id)mappingForClass:(Class)objectClass withBlock:(void (^)(RKObjectMapping*))block { ++ (id)mappingForClass:(Class)objectClass withBlock:(void (^)(RKObjectMapping *))block +{ return [self mappingForClass:objectClass usingBlock:block]; } -+ (id)mappingForClass:(Class)objectClass block:(void (^)(RKObjectMapping*))block { ++ (id)mappingForClass:(Class)objectClass block:(void (^)(RKObjectMapping *))block +{ return [self mappingForClass:objectClass usingBlock:block]; } -+ (id)serializationMappingWithBlock:(void (^)(RKObjectMapping*))block { - RKObjectMapping* mapping = [self serializationMapping]; ++ (id)serializationMappingWithBlock:(void (^)(RKObjectMapping *))block +{ + RKObjectMapping *mapping = [self serializationMapping]; block(mapping); return mapping; } #endif // NS_BLOCKS_AVAILABLE -- (id)init { +- (id)init +{ self = [super init]; if (self) { _mappings = [NSMutableArray new]; @@ -98,7 +107,8 @@ - (id)init { return self; } -- (id)copyWithZone:(NSZone *)zone { +- (id)copyWithZone:(NSZone *)zone +{ RKObjectMapping *copy = [[[self class] allocWithZone:zone] init]; copy.objectClass = self.objectClass; copy.rootKeyPath = self.rootKeyPath; @@ -116,7 +126,8 @@ - (id)copyWithZone:(NSZone *)zone { return copy; } -- (void)dealloc { +- (void)dealloc +{ [_rootKeyPath release]; [_mappings release]; [_dateFormatters release]; @@ -124,21 +135,25 @@ - (void)dealloc { [super dealloc]; } -- (NSString *)objectClassName { +- (NSString *)objectClassName +{ return NSStringFromClass(self.objectClass); } -- (void)setObjectClassName:(NSString *)objectClassName { +- (void)setObjectClassName:(NSString *)objectClassName +{ self.objectClass = NSClassFromString(objectClassName); } -- (NSArray *)mappedKeyPaths { +- (NSArray *)mappedKeyPaths +{ return [_mappings valueForKey:@"destinationKeyPath"]; } -- (NSArray *)attributeMappings { - NSMutableArray* mappings = [NSMutableArray array]; - for (RKObjectAttributeMapping* mapping in self.mappings) { +- (NSArray *)attributeMappings +{ + NSMutableArray *mappings = [NSMutableArray array]; + for (RKObjectAttributeMapping *mapping in self.mappings) { if ([mapping isMemberOfClass:[RKObjectAttributeMapping class]]) { [mappings addObject:mapping]; } @@ -147,9 +162,10 @@ - (NSArray *)attributeMappings { return mappings; } -- (NSArray *)relationshipMappings { - NSMutableArray* mappings = [NSMutableArray array]; - for (RKObjectAttributeMapping* mapping in self.mappings) { +- (NSArray *)relationshipMappings +{ + NSMutableArray *mappings = [NSMutableArray array]; + for (RKObjectAttributeMapping *mapping in self.mappings) { if ([mapping isMemberOfClass:[RKObjectRelationshipMapping class]]) { [mappings addObject:mapping]; } @@ -158,25 +174,30 @@ - (NSArray *)relationshipMappings { return mappings; } -- (void)addAttributeMapping:(RKObjectAttributeMapping*)mapping { +- (void)addAttributeMapping:(RKObjectAttributeMapping *)mapping +{ NSAssert1([[self mappedKeyPaths] containsObject:mapping.destinationKeyPath] == NO, @"Unable to add mapping for keyPath %@, one already exists...", mapping.destinationKeyPath); [_mappings addObject:mapping]; } -- (void)addRelationshipMapping:(RKObjectRelationshipMapping*)mapping { +- (void)addRelationshipMapping:(RKObjectRelationshipMapping *)mapping +{ [self addAttributeMapping:mapping]; } -- (NSString *)description { +- (NSString *)description +{ return [NSString stringWithFormat:@"<%@:%p objectClass=%@ keyPath mappings => %@>", NSStringFromClass([self class]), self, NSStringFromClass(self.objectClass), _mappings]; } -- (id)mappingForKeyPath:(NSString *)keyPath { +- (id)mappingForKeyPath:(NSString *)keyPath +{ return [self mappingForSourceKeyPath:keyPath]; } -- (id)mappingForSourceKeyPath:(NSString *)sourceKeyPath { - for (RKObjectAttributeMapping* mapping in _mappings) { +- (id)mappingForSourceKeyPath:(NSString *)sourceKeyPath +{ + for (RKObjectAttributeMapping *mapping in _mappings) { if ([mapping.sourceKeyPath isEqualToString:sourceKeyPath]) { return mapping; } @@ -185,8 +206,9 @@ - (id)mappingForSourceKeyPath:(NSString *)sourceKeyPath { return nil; } -- (id)mappingForDestinationKeyPath:(NSString *)destinationKeyPath { - for (RKObjectAttributeMapping* mapping in _mappings) { +- (id)mappingForDestinationKeyPath:(NSString *)destinationKeyPath +{ + for (RKObjectAttributeMapping *mapping in _mappings) { if ([mapping.destinationKeyPath isEqualToString:destinationKeyPath]) { return mapping; } @@ -195,18 +217,20 @@ - (id)mappingForDestinationKeyPath:(NSString *)destinationKeyPath { return nil; } -- (void)mapAttributesCollection:(id)attributes { - for (NSString* attributeKeyPath in attributes) { +- (void)mapAttributesCollection:(id)attributes +{ + for (NSString *attributeKeyPath in attributes) { [self addAttributeMapping:[RKObjectAttributeMapping mappingFromKeyPath:attributeKeyPath toKeyPath:attributeKeyPath]]; } } -- (void)mapAttributes:(NSString*)attributeKeyPath, ... { +- (void)mapAttributes:(NSString *)attributeKeyPath, ... +{ va_list args; va_start(args, attributeKeyPath); - NSMutableSet* attributeKeyPaths = [NSMutableSet set]; + NSMutableSet *attributeKeyPaths = [NSMutableSet set]; - for (NSString* keyPath = attributeKeyPath; keyPath != nil; keyPath = va_arg(args, NSString*)) { + for (NSString *keyPath = attributeKeyPath; keyPath != nil; keyPath = va_arg(args, NSString *)) { [attributeKeyPaths addObject:keyPath]; } @@ -215,86 +239,100 @@ - (void)mapAttributes:(NSString*)attributeKeyPath, ... { [self mapAttributesCollection:attributeKeyPaths]; } -- (void)mapAttributesFromSet:(NSSet *)set { +- (void)mapAttributesFromSet:(NSSet *)set +{ [self mapAttributesCollection:set]; } -- (void)mapAttributesFromArray:(NSArray *)array { +- (void)mapAttributesFromArray:(NSArray *)array +{ [self mapAttributesCollection:[NSSet setWithArray:array]]; } -- (void)mapKeyPath:(NSString *)relationshipKeyPath toRelationship:(NSString*)keyPath withMapping:(RKObjectMappingDefinition *)objectOrDynamicMapping serialize:(BOOL)serialize { - RKObjectRelationshipMapping* mapping = [RKObjectRelationshipMapping mappingFromKeyPath:relationshipKeyPath toKeyPath:keyPath withMapping:objectOrDynamicMapping reversible:serialize]; +- (void)mapKeyPath:(NSString *)relationshipKeyPath toRelationship:(NSString *)keyPath withMapping:(RKObjectMappingDefinition *)objectOrDynamicMapping serialize:(BOOL)serialize +{ + RKObjectRelationshipMapping *mapping = [RKObjectRelationshipMapping mappingFromKeyPath:relationshipKeyPath toKeyPath:keyPath withMapping:objectOrDynamicMapping reversible:serialize]; [self addRelationshipMapping:mapping]; } -- (void)mapKeyPath:(NSString *)relationshipKeyPath toRelationship:(NSString*)keyPath withMapping:(RKObjectMappingDefinition *)objectOrDynamicMapping { +- (void)mapKeyPath:(NSString *)relationshipKeyPath toRelationship:(NSString *)keyPath withMapping:(RKObjectMappingDefinition *)objectOrDynamicMapping +{ [self mapKeyPath:relationshipKeyPath toRelationship:keyPath withMapping:objectOrDynamicMapping serialize:YES]; } -- (void)mapRelationship:(NSString*)relationshipKeyPath withMapping:(RKObjectMappingDefinition *)objectOrDynamicMapping { +- (void)mapRelationship:(NSString *)relationshipKeyPath withMapping:(RKObjectMappingDefinition *)objectOrDynamicMapping +{ [self mapKeyPath:relationshipKeyPath toRelationship:relationshipKeyPath withMapping:objectOrDynamicMapping]; } -- (void)mapKeyPath:(NSString*)sourceKeyPath toAttribute:(NSString*)destinationKeyPath { - RKObjectAttributeMapping* mapping = [RKObjectAttributeMapping mappingFromKeyPath:sourceKeyPath toKeyPath:destinationKeyPath]; +- (void)mapKeyPath:(NSString *)sourceKeyPath toAttribute:(NSString *)destinationKeyPath +{ + RKObjectAttributeMapping *mapping = [RKObjectAttributeMapping mappingFromKeyPath:sourceKeyPath toKeyPath:destinationKeyPath]; [self addAttributeMapping:mapping]; } -- (void)hasMany:(NSString*)keyPath withMapping:(RKObjectMappingDefinition *)objectOrDynamicMapping { +- (void)hasMany:(NSString *)keyPath withMapping:(RKObjectMappingDefinition *)objectOrDynamicMapping +{ [self mapRelationship:keyPath withMapping:objectOrDynamicMapping]; } -- (void)hasOne:(NSString*)keyPath withMapping:(RKObjectMappingDefinition *)objectOrDynamicMapping { +- (void)hasOne:(NSString *)keyPath withMapping:(RKObjectMappingDefinition *)objectOrDynamicMapping +{ [self mapRelationship:keyPath withMapping:objectOrDynamicMapping]; } -- (void)removeAllMappings { +- (void)removeAllMappings +{ [_mappings removeAllObjects]; } -- (void)removeMapping:(RKObjectAttributeMapping*)attributeOrRelationshipMapping { +- (void)removeMapping:(RKObjectAttributeMapping *)attributeOrRelationshipMapping +{ [_mappings removeObject:attributeOrRelationshipMapping]; } -- (void)removeMappingForKeyPath:(NSString*)keyPath { - RKObjectAttributeMapping* mapping = [self mappingForKeyPath:keyPath]; +- (void)removeMappingForKeyPath:(NSString *)keyPath +{ + RKObjectAttributeMapping *mapping = [self mappingForKeyPath:keyPath]; [self removeMapping:mapping]; } #ifndef MAX_INVERSE_MAPPING_RECURSION_DEPTH #define MAX_INVERSE_MAPPING_RECURSION_DEPTH (100) #endif -- (RKObjectMapping*)inverseMappingAtDepth:(NSInteger)depth { +- (RKObjectMapping *)inverseMappingAtDepth:(NSInteger)depth +{ NSAssert(depth < MAX_INVERSE_MAPPING_RECURSION_DEPTH, @"Exceeded max recursion level in inverseMapping. This is likely due to a loop in the serialization graph. To break this loop, specify one-way relationships by setting serialize to NO in mapKeyPath:toRelationship:withObjectMapping:serialize:"); - RKObjectMapping* inverseMapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; - for (RKObjectAttributeMapping* attributeMapping in self.attributeMappings) { + RKObjectMapping *inverseMapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; + for (RKObjectAttributeMapping *attributeMapping in self.attributeMappings) { [inverseMapping mapKeyPath:attributeMapping.destinationKeyPath toAttribute:attributeMapping.sourceKeyPath]; } - for (RKObjectRelationshipMapping* relationshipMapping in self.relationshipMappings) { + for (RKObjectRelationshipMapping *relationshipMapping in self.relationshipMappings) { if (relationshipMapping.reversible) { - RKObjectMappingDefinition * mapping = relationshipMapping.mapping; + RKObjectMappingDefinition *mapping = relationshipMapping.mapping; if (! [mapping isKindOfClass:[RKObjectMapping class]]) { RKLogWarning(@"Unable to generate inverse mapping for relationship '%@': %@ relationships cannot be inversed.", relationshipMapping.sourceKeyPath, NSStringFromClass([mapping class])); continue; } - [inverseMapping mapKeyPath:relationshipMapping.destinationKeyPath toRelationship:relationshipMapping.sourceKeyPath withMapping:[(RKObjectMapping*)mapping inverseMappingAtDepth:depth+1]]; + [inverseMapping mapKeyPath:relationshipMapping.destinationKeyPath toRelationship:relationshipMapping.sourceKeyPath withMapping:[(RKObjectMapping *)mapping inverseMappingAtDepth:depth+1]]; } } return inverseMapping; } -- (RKObjectMapping*)inverseMapping { +- (RKObjectMapping *)inverseMapping +{ return [self inverseMappingAtDepth:0]; } -- (void)mapKeyPathsToAttributes:(NSString*)firstKeyPath, ... { +- (void)mapKeyPathsToAttributes:(NSString *)firstKeyPath, ... +{ va_list args; va_start(args, firstKeyPath); - for (NSString* keyPath = firstKeyPath; keyPath != nil; keyPath = va_arg(args, NSString*)) { - NSString* attributeKeyPath = va_arg(args, NSString*); + for (NSString *keyPath = firstKeyPath; keyPath != nil; keyPath = va_arg(args, NSString *)) { + NSString *attributeKeyPath = va_arg(args, NSString *); NSAssert(attributeKeyPath != nil, @"Cannot map a keyPath without a destination attribute keyPath"); [self mapKeyPath:keyPath toAttribute:attributeKeyPath]; // TODO: Raise proper exception here, argument error... @@ -302,16 +340,19 @@ - (void)mapKeyPathsToAttributes:(NSString*)firstKeyPath, ... { va_end(args); } -- (void)mapKeyOfNestedDictionaryToAttribute:(NSString*)attributeName { +- (void)mapKeyOfNestedDictionaryToAttribute:(NSString *)attributeName +{ [self mapKeyPath:RKObjectMappingNestingAttributeKeyName toAttribute:attributeName]; } -- (RKObjectAttributeMapping *)attributeMappingForKeyOfNestedDictionary { +- (RKObjectAttributeMapping *)attributeMappingForKeyOfNestedDictionary +{ return [self mappingForKeyPath:RKObjectMappingNestingAttributeKeyName]; } -- (RKObjectAttributeMapping*)mappingForAttribute:(NSString*)attributeKey { - for (RKObjectAttributeMapping* mapping in [self attributeMappings]) { +- (RKObjectAttributeMapping *)mappingForAttribute:(NSString *)attributeKey +{ + for (RKObjectAttributeMapping *mapping in [self attributeMappings]) { if ([mapping.destinationKeyPath isEqualToString:attributeKey]) { return mapping; } @@ -320,8 +361,9 @@ - (RKObjectAttributeMapping*)mappingForAttribute:(NSString*)attributeKey { return nil; } -- (RKObjectRelationshipMapping*)mappingForRelationship:(NSString*)relationshipKey { - for (RKObjectRelationshipMapping* mapping in [self relationshipMappings]) { +- (RKObjectRelationshipMapping *)mappingForRelationship:(NSString *)relationshipKey +{ + for (RKObjectRelationshipMapping *mapping in [self relationshipMappings]) { if ([mapping.destinationKeyPath isEqualToString:relationshipKey]) { return mapping; } @@ -330,25 +372,30 @@ - (RKObjectRelationshipMapping*)mappingForRelationship:(NSString*)relationshipKe return nil; } -- (id)defaultValueForMissingAttribute:(NSString*)attributeName { +- (id)defaultValueForMissingAttribute:(NSString *)attributeName +{ return nil; } -- (id)mappableObjectForData:(id)mappableData { +- (id)mappableObjectForData:(id)mappableData +{ return [[self.objectClass new] autorelease]; } -- (Class)classForProperty:(NSString*)propertyName { +- (Class)classForProperty:(NSString *)propertyName +{ return [[RKObjectPropertyInspector sharedInspector] typeForProperty:propertyName ofClass:self.objectClass]; } #pragma mark - Date and Time -- (NSFormatter *)preferredDateFormatter { +- (NSFormatter *)preferredDateFormatter +{ return _preferredDateFormatter ? _preferredDateFormatter : [RKObjectMapping preferredDateFormatter]; } -- (NSArray *)dateFormatters { +- (NSArray *)dateFormatters +{ return _dateFormatters ? _dateFormatters : [RKObjectMapping defaultDateFormatters]; } @@ -361,7 +408,8 @@ - (NSArray *)dateFormatters { @implementation RKObjectMapping (DateAndTimeFormatting) -+ (NSArray *)defaultDateFormatters { ++ (NSArray *)defaultDateFormatters +{ if (!defaultDateFormatters) { defaultDateFormatters = [[NSMutableArray alloc] initWithCapacity:2]; @@ -377,7 +425,8 @@ + (NSArray *)defaultDateFormatters { return defaultDateFormatters; } -+ (void)setDefaultDateFormatters:(NSArray *)dateFormatters { ++ (void)setDefaultDateFormatters:(NSArray *)dateFormatters +{ [defaultDateFormatters release]; defaultDateFormatters = nil; if (dateFormatters) { @@ -386,12 +435,14 @@ + (void)setDefaultDateFormatters:(NSArray *)dateFormatters { } -+ (void)addDefaultDateFormatter:(id)dateFormatter { ++ (void)addDefaultDateFormatter:(id)dateFormatter +{ [self defaultDateFormatters]; [defaultDateFormatters insertObject:dateFormatter atIndex:0]; } -+ (void)addDefaultDateFormatterForString:(NSString *)dateFormatString inTimeZone:(NSTimeZone *)nilOrTimeZone { ++ (void)addDefaultDateFormatterForString:(NSString *)dateFormatString inTimeZone:(NSTimeZone *)nilOrTimeZone +{ NSDateFormatter *dateFormatter = [NSDateFormatter new]; dateFormatter.dateFormat = dateFormatString; dateFormatter.locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]; @@ -406,7 +457,8 @@ + (void)addDefaultDateFormatterForString:(NSString *)dateFormatString inTimeZone } -+ (NSFormatter *)preferredDateFormatter { ++ (NSFormatter *)preferredDateFormatter +{ if (!preferredDateFormatter) { // A date formatter that matches the output of [NSDate description] preferredDateFormatter = [NSDateFormatter new]; @@ -418,7 +470,8 @@ + (NSFormatter *)preferredDateFormatter { return preferredDateFormatter; } -+ (void)setPreferredDateFormatter:(NSDateFormatter *)dateFormatter { ++ (void)setPreferredDateFormatter:(NSDateFormatter *)dateFormatter +{ [dateFormatter retain]; [preferredDateFormatter release]; preferredDateFormatter = dateFormatter; diff --git a/Code/ObjectMapping/RKObjectMappingOperation.m b/Code/ObjectMapping/RKObjectMappingOperation.m index 711150e194..4fd20bcd9e 100644 --- a/Code/ObjectMapping/RKObjectMappingOperation.m +++ b/Code/ObjectMapping/RKObjectMappingOperation.m @@ -57,7 +57,7 @@ BOOL RKObjectIsValueEqualToValue(id sourceValue, id destinationValue) { // Comparison magic using function pointers. See this page for details: http://www.red-sweater.com/blog/320/abusing-objective-c-with-class // Original code courtesy of Greg Parker // This is necessary because isEqualToNumber will return negative integer values that aren't coercable directly to BOOL's without help [sbw] - BOOL (*ComparisonSender)(id, SEL, id) = (BOOL (*)(id, SEL, id)) objc_msgSend; + BOOL (*ComparisonSender)(id, SEL, id) = (BOOL (*)(id, SEL, id))objc_msgSend; return ComparisonSender(sourceValue, comparisonSelector, destinationValue); } @@ -76,7 +76,8 @@ @implementation RKObjectMappingOperation @synthesize nestedAttributeSubstitution = _nestedAttributeSubstitution; @synthesize validationError = _validationError; -+ (id)mappingOperationFromObject:(id)sourceObject toObject:(id)destinationObject withMapping:(RKObjectMappingDefinition *)objectMapping { ++ (id)mappingOperationFromObject:(id)sourceObject toObject:(id)destinationObject withMapping:(RKObjectMappingDefinition *)objectMapping +{ // Check for availability of ManagedObjectMappingOperation. Better approach for handling? Class targetClass = NSClassFromString(@"RKManagedObjectMappingOperation"); if (targetClass == nil) targetClass = [RKObjectMappingOperation class]; @@ -84,7 +85,8 @@ + (id)mappingOperationFromObject:(id)sourceObject toObject:(id)destinationObject return [[[targetClass alloc] initWithSourceObject:sourceObject destinationObject:destinationObject mapping:objectMapping] autorelease]; } -- (id)initWithSourceObject:(id)sourceObject destinationObject:(id)destinationObject mapping:(RKObjectMappingDefinition *)objectMapping { +- (id)initWithSourceObject:(id)sourceObject destinationObject:(id)destinationObject mapping:(RKObjectMappingDefinition *)objectMapping +{ NSAssert(sourceObject != nil, @"Cannot perform a mapping operation without a sourceObject object"); NSAssert(destinationObject != nil, @"Cannot perform a mapping operation without a destinationObject"); NSAssert(objectMapping != nil, @"Cannot perform a mapping operation without a mapping"); @@ -95,10 +97,10 @@ - (id)initWithSourceObject:(id)sourceObject destinationObject:(id)destinationObj _destinationObject = [destinationObject retain]; if ([objectMapping isKindOfClass:[RKDynamicObjectMapping class]]) { - _objectMapping = [[(RKDynamicObjectMapping*)objectMapping objectMappingForDictionary:_sourceObject] retain]; + _objectMapping = [[(RKDynamicObjectMapping *)objectMapping objectMappingForDictionary:_sourceObject] retain]; RKLogDebug(@"RKObjectMappingOperation was initialized with a dynamic mapping. Determined concrete mapping = %@", _objectMapping); } else if ([objectMapping isKindOfClass:[RKObjectMapping class]]) { - _objectMapping = (RKObjectMapping*)[objectMapping retain]; + _objectMapping = (RKObjectMapping *)[objectMapping retain]; } NSAssert(_objectMapping, @"Cannot perform a mapping operation with an object mapping"); } @@ -106,7 +108,8 @@ - (id)initWithSourceObject:(id)sourceObject destinationObject:(id)destinationObj return self; } -- (void)dealloc { +- (void)dealloc +{ [_sourceObject release]; [_destinationObject release]; [_objectMapping release]; @@ -116,10 +119,11 @@ - (void)dealloc { [super dealloc]; } -- (NSDate*)parseDateFromString:(NSString*)string { +- (NSDate *)parseDateFromString:(NSString *)string +{ RKLogTrace(@"Transforming string value '%@' to NSDate...", string); - NSDate* date = nil; + NSDate *date = nil; NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init]; numberFormatter.numberStyle = NSNumberFormatterDecimalStyle; @@ -130,7 +134,7 @@ - (NSDate*)parseDateFromString:(NSString*)string { if (numeric) { date = [NSDate dateWithTimeIntervalSince1970:[numeric doubleValue]]; - } else if(![string isEqualToString:@""]) { + } else if (![string isEqualToString:@""]) { for (NSFormatter *dateFormatter in self.objectMapping.dateFormatters) { BOOL success; @synchronized(dateFormatter) { @@ -155,7 +159,8 @@ - (NSDate*)parseDateFromString:(NSString*)string { return date; } -- (id)transformValue:(id)value atKeyPath:(NSString *)keyPath toType:(Class)destinationType { +- (id)transformValue:(id)value atKeyPath:(NSString *)keyPath toType:(Class)destinationType +{ RKLogTrace(@"Found transformable value at keyPath '%@'. Transforming from type '%@' to '%@'", keyPath, NSStringFromClass([value class]), NSStringFromClass(destinationType)); Class sourceType = [value class]; Class orderedSetClass = NSClassFromString(@"NSOrderedSet"); @@ -163,23 +168,23 @@ - (id)transformValue:(id)value atKeyPath:(NSString *)keyPath toType:(Class)desti if ([sourceType isSubclassOfClass:[NSString class]]) { if ([destinationType isSubclassOfClass:[NSDate class]]) { // String -> Date - return [self parseDateFromString:(NSString*)value]; + return [self parseDateFromString:(NSString *)value]; } else if ([destinationType isSubclassOfClass:[NSURL class]]) { // String -> URL - return [NSURL URLWithString:(NSString*)value]; + return [NSURL URLWithString:(NSString *)value]; } else if ([destinationType isSubclassOfClass:[NSDecimalNumber class]]) { // String -> Decimal Number - return [NSDecimalNumber decimalNumberWithString:(NSString*)value]; + return [NSDecimalNumber decimalNumberWithString:(NSString *)value]; } else if ([destinationType isSubclassOfClass:[NSNumber class]]) { // String -> Number - NSString* lowercasedString = [(NSString*)value lowercaseString]; - NSSet* trueStrings = [NSSet setWithObjects:@"true", @"t", @"yes", nil]; - NSSet* booleanStrings = [trueStrings setByAddingObjectsFromSet:[NSSet setWithObjects:@"false", @"f", @"no", nil]]; + NSString *lowercasedString = [(NSString *)value lowercaseString]; + NSSet *trueStrings = [NSSet setWithObjects:@"true", @"t", @"yes", nil]; + NSSet *booleanStrings = [trueStrings setByAddingObjectsFromSet:[NSSet setWithObjects:@"false", @"f", @"no", nil]]; if ([booleanStrings containsObject:lowercasedString]) { // Handle booleans encoded as Strings return [NSNumber numberWithBool:[trueStrings containsObject:lowercasedString]]; } else { - return [NSNumber numberWithDouble:[(NSString*)value doubleValue]]; + return [NSNumber numberWithDouble:[(NSString *)value doubleValue]]; } } } else if (value == [NSNull null] || [value isEqual:[NSNull null]]) { @@ -188,7 +193,7 @@ - (id)transformValue:(id)value atKeyPath:(NSString *)keyPath toType:(Class)desti } else if ([sourceType isSubclassOfClass:[NSSet class]]) { // Set -> Array if ([destinationType isSubclassOfClass:[NSArray class]]) { - return [(NSSet*)value allObjects]; + return [(NSSet *)value allObjects]; } } else if (orderedSetClass && [sourceType isSubclassOfClass:orderedSetClass]) { // OrderedSet -> Array @@ -207,11 +212,11 @@ - (id)transformValue:(id)value atKeyPath:(NSString *)keyPath toType:(Class)desti } else if ([sourceType isSubclassOfClass:[NSNumber class]] && [destinationType isSubclassOfClass:[NSDate class]]) { // Number -> Date if ([destinationType isSubclassOfClass:[NSDate class]]) { - return [NSDate dateWithTimeIntervalSince1970:[(NSNumber*)value intValue]]; + return [NSDate dateWithTimeIntervalSince1970:[(NSNumber *)value intValue]]; } else if ([sourceType isSubclassOfClass:NSClassFromString(@"__NSCFBoolean")] && [destinationType isSubclassOfClass:[NSString class]]) { return ([value boolValue] ? @"true" : @"false"); } - return [NSDate dateWithTimeIntervalSince1970:[(NSNumber*)value doubleValue]]; + return [NSDate dateWithTimeIntervalSince1970:[(NSNumber *)value doubleValue]]; } else if ([sourceType isSubclassOfClass:[NSNumber class]] && [destinationType isSubclassOfClass:[NSDecimalNumber class]]) { // Number -> Decimal Number return [NSDecimalNumber decimalNumberWithDecimal:[value decimalValue]]; @@ -220,7 +225,7 @@ - (id)transformValue:(id)value atKeyPath:(NSString *)keyPath toType:(Class)desti [destinationType isSubclassOfClass:[NSString class]]) { return ([value boolValue] ? @"true" : @"false"); if ([destinationType isSubclassOfClass:[NSDate class]]) { - return [NSDate dateWithTimeIntervalSince1970:[(NSNumber*)value intValue]]; + return [NSDate dateWithTimeIntervalSince1970:[(NSNumber *)value intValue]]; } else if (([sourceType isSubclassOfClass:NSClassFromString(@"__NSCFBoolean")] || [sourceType isSubclassOfClass:NSClassFromString(@"NSCFBoolean")]) && [destinationType isSubclassOfClass:[NSString class]]) { return ([value boolValue] ? @"true" : @"false"); } @@ -229,7 +234,7 @@ - (id)transformValue:(id)value atKeyPath:(NSString *)keyPath toType:(Class)desti } else if ([destinationType isSubclassOfClass:[NSString class]] && [value isKindOfClass:[NSDate class]]) { // NSDate -> NSString // Transform using the preferred date formatter - NSString* dateString = nil; + NSString *dateString = nil; @synchronized(self.objectMapping.preferredDateFormatter) { dateString = [self.objectMapping.preferredDateFormatter stringForObjectValue:value]; } @@ -241,18 +246,20 @@ - (id)transformValue:(id)value atKeyPath:(NSString *)keyPath toType:(Class)desti return nil; } -- (BOOL)isValue:(id)sourceValue equalToValue:(id)destinationValue { +- (BOOL)isValue:(id)sourceValue equalToValue:(id)destinationValue +{ return RKObjectIsValueEqualToValue(sourceValue, destinationValue); } -- (BOOL)validateValue:(id *)value atKeyPath:(NSString*)keyPath { +- (BOOL)validateValue:(id *)value atKeyPath:(NSString *)keyPath +{ BOOL success = YES; if (self.objectMapping.performKeyValueValidation && [self.destinationObject respondsToSelector:@selector(validateValue:forKeyPath:error:)]) { success = [self.destinationObject validateValue:value forKeyPath:keyPath error:&_validationError]; if (!success) { if (_validationError) { - RKLogError(@"Validation failed while mapping attribute at key path '%@' to value %@. Error: %@", keyPath, *value, [_validationError localizedDescription]); + RKLogError(@"Validation failed while mapping attribute at key path '%@' to value %@. Error: %@", keyPath, *value, [_validationError localizedDescription]); RKLogValidationError(_validationError); } else { RKLogWarning(@"Destination object %@ rejected attribute value %@ for keyPath %@. Skipping...", self.destinationObject, *value, keyPath); @@ -263,7 +270,8 @@ - (BOOL)validateValue:(id *)value atKeyPath:(NSString*)keyPath { return success; } -- (BOOL)shouldSetValue:(id *)value atKeyPath:(NSString*)keyPath { +- (BOOL)shouldSetValue:(id *)value atKeyPath:(NSString *)keyPath +{ id currentValue = [self.destinationObject valueForKeyPath:keyPath]; if (currentValue == [NSNull null] || [currentValue isEqual:[NSNull null]]) { currentValue = nil; @@ -296,13 +304,14 @@ - (BOOL)shouldSetValue:(id *)value atKeyPath:(NSString*)keyPath { return NO; } -- (NSArray*)applyNestingToMappings:(NSArray*)mappings { +- (NSArray *)applyNestingToMappings:(NSArray *)mappings +{ if (_nestedAttributeSubstitution) { - NSString* searchString = [NSString stringWithFormat:@"(%@)", [[_nestedAttributeSubstitution allKeys] lastObject]]; - NSString* replacementString = [[_nestedAttributeSubstitution allValues] lastObject]; - NSMutableArray* array = [NSMutableArray arrayWithCapacity:[self.objectMapping.attributeMappings count]]; - for (RKObjectAttributeMapping* mapping in mappings) { - RKObjectAttributeMapping* nestedMapping = [mapping copy]; + NSString *searchString = [NSString stringWithFormat:@"(%@)", [[_nestedAttributeSubstitution allKeys] lastObject]]; + NSString *replacementString = [[_nestedAttributeSubstitution allValues] lastObject]; + NSMutableArray *array = [NSMutableArray arrayWithCapacity:[self.objectMapping.attributeMappings count]]; + for (RKObjectAttributeMapping *mapping in mappings) { + RKObjectAttributeMapping *nestedMapping = [mapping copy]; nestedMapping.sourceKeyPath = [nestedMapping.sourceKeyPath stringByReplacingOccurrencesOfString:searchString withString:replacementString]; nestedMapping.destinationKeyPath = [nestedMapping.destinationKeyPath stringByReplacingOccurrencesOfString:searchString withString:replacementString]; [array addObject:nestedMapping]; @@ -315,15 +324,18 @@ - (NSArray*)applyNestingToMappings:(NSArray*)mappings { return mappings; } -- (NSArray*)attributeMappings { +- (NSArray *)attributeMappings +{ return [self applyNestingToMappings:self.objectMapping.attributeMappings]; } -- (NSArray*)relationshipMappings { +- (NSArray *)relationshipMappings +{ return [self applyNestingToMappings:self.objectMapping.relationshipMappings]; } -- (void)applyAttributeMapping:(RKObjectAttributeMapping*)attributeMapping withValue:(id)value { +- (void)applyAttributeMapping:(RKObjectAttributeMapping *)attributeMapping withValue:(id)value +{ if ([self.delegate respondsToSelector:@selector(objectMappingOperation:didFindMapping:forKeyPath:)]) { [self.delegate objectMappingOperation:self didFindMapping:attributeMapping forKeyPath:attributeMapping.sourceKeyPath]; } @@ -352,7 +364,8 @@ - (void)applyAttributeMapping:(RKObjectAttributeMapping*)attributeMapping withVa } // Return YES if we mapped any attributes -- (BOOL)applyAttributeMappings { +- (BOOL)applyAttributeMappings +{ // If we have a nesting substitution value, we have alread BOOL appliedMappings = (_nestedAttributeSubstitution != nil); @@ -360,7 +373,7 @@ - (BOOL)applyAttributeMappings { RKLogDebug(@"Key-value validation is disabled for mapping, skipping..."); } - for (RKObjectAttributeMapping* attributeMapping in [self attributeMappings]) { + for (RKObjectAttributeMapping *attributeMapping in [self attributeMappings]) { if ([attributeMapping isMappingForKeyOfNestedDictionary]) { RKLogTrace(@"Skipping attribute mapping for special keyPath '%@'", attributeMapping.sourceKeyPath); continue; @@ -415,25 +428,28 @@ - (BOOL)applyAttributeMappings { return appliedMappings; } -- (BOOL)isTypeACollection:(Class)type { +- (BOOL)isTypeACollection:(Class)type +{ Class orderedSetClass = NSClassFromString(@"NSOrderedSet"); return (type && ([type isSubclassOfClass:[NSSet class]] || [type isSubclassOfClass:[NSArray class]] || (orderedSetClass && [type isSubclassOfClass:orderedSetClass]))); } -- (BOOL)isValueACollection:(id)value { +- (BOOL)isValueACollection:(id)value +{ return [self isTypeACollection:[value class]]; } -- (BOOL)mapNestedObject:(id)anObject toObject:(id)anotherObject withRealtionshipMapping:(RKObjectRelationshipMapping*)relationshipMapping { +- (BOOL)mapNestedObject:(id)anObject toObject:(id)anotherObject withRealtionshipMapping:(RKObjectRelationshipMapping *)relationshipMapping +{ NSAssert(anObject, @"Cannot map nested object without a nested source object"); NSAssert(anotherObject, @"Cannot map nested object without a destination object"); NSAssert(relationshipMapping, @"Cannot map a nested object relationship without a relationship mapping"); - NSError* error = nil; + NSError *error = nil; RKLogTrace(@"Performing nested object mapping using mapping %@ for data: %@", relationshipMapping, anObject); - RKObjectMappingOperation* subOperation = [RKObjectMappingOperation mappingOperationFromObject:anObject toObject:anotherObject withMapping:relationshipMapping.mapping]; + RKObjectMappingOperation *subOperation = [RKObjectMappingOperation mappingOperationFromObject:anObject toObject:anotherObject withMapping:relationshipMapping.mapping]; subOperation.delegate = self.delegate; subOperation.queue = self.queue; if (NO == [subOperation performMapping:&error]) { @@ -443,11 +459,12 @@ - (BOOL)mapNestedObject:(id)anObject toObject:(id)anotherObject withRealtionship return YES; } -- (BOOL)applyRelationshipMappings { +- (BOOL)applyRelationshipMappings +{ BOOL appliedMappings = NO; id destinationObject = nil; - for (RKObjectRelationshipMapping* relationshipMapping in [self relationshipMappings]) { + for (RKObjectRelationshipMapping *relationshipMapping in [self relationshipMappings]) { id value = nil; @try { value = [self.sourceObject valueForKeyPath:relationshipMapping.sourceKeyPath]; @@ -480,10 +497,10 @@ - (BOOL)applyRelationshipMappings { // If we have forced mapping of a dictionary, map each subdictionary if ([value isKindOfClass:[NSDictionary class]]) { RKLogDebug(@"Collection mapping forced for NSDictionary, mapping each key/value independently..."); - NSArray* objectsToMap = [NSMutableArray arrayWithCapacity:[value count]]; + NSArray *objectsToMap = [NSMutableArray arrayWithCapacity:[value count]]; for (id key in value) { - NSDictionary* dictionaryToMap = [NSDictionary dictionaryWithObject:[value valueForKey:key] forKey:key]; - [(NSMutableArray*)objectsToMap addObject:dictionaryToMap]; + NSDictionary *dictionaryToMap = [NSDictionary dictionaryWithObject:[value valueForKey:key] forKey:key]; + [(NSMutableArray *)objectsToMap addObject:dictionaryToMap]; } value = objectsToMap; } else { @@ -522,16 +539,16 @@ - (BOOL)applyRelationshipMappings { RKLogWarning(@"Key path '%@' yielded collection containing another collection rather than a collection of objects: %@", relationshipMapping.sourceKeyPath, value); } for (id nestedObject in value) { - RKObjectMappingDefinition * mapping = relationshipMapping.mapping; - RKObjectMapping* objectMapping = nil; + RKObjectMappingDefinition *mapping = relationshipMapping.mapping; + RKObjectMapping *objectMapping = nil; if ([mapping isKindOfClass:[RKDynamicObjectMapping class]]) { - objectMapping = [(RKDynamicObjectMapping*)mapping objectMappingForDictionary:nestedObject]; + objectMapping = [(RKDynamicObjectMapping *)mapping objectMappingForDictionary:nestedObject]; if (! objectMapping) { RKLogDebug(@"Mapping %@ declined mapping for data %@: returned nil objectMapping", mapping, nestedObject); continue; } } else if ([mapping isKindOfClass:[RKObjectMapping class]]) { - objectMapping = (RKObjectMapping*)mapping; + objectMapping = (RKObjectMapping *)mapping; } else { NSAssert(objectMapping, @"Encountered unknown mapping type '%@'", NSStringFromClass([mapping class])); } @@ -555,11 +572,11 @@ - (BOOL)applyRelationshipMappings { RKLogTrace(@"Found a managedObject collection. About to apply value via mutable[Set|Array]ValueForKey"); if ([destinationObject isKindOfClass:[NSSet class]]) { RKLogTrace(@"Mapped NSSet relationship object from keyPath '%@' to '%@'. Value: %@", relationshipMapping.sourceKeyPath, relationshipMapping.destinationKeyPath, destinationObject); - NSMutableSet* destinationSet = [self.destinationObject mutableSetValueForKey:relationshipMapping.destinationKeyPath]; + NSMutableSet *destinationSet = [self.destinationObject mutableSetValueForKey:relationshipMapping.destinationKeyPath]; [destinationSet setSet:destinationObject]; } else if ([destinationObject isKindOfClass:[NSArray class]]) { RKLogTrace(@"Mapped NSArray relationship object from keyPath '%@' to '%@'. Value: %@", relationshipMapping.sourceKeyPath, relationshipMapping.destinationKeyPath, destinationObject); - NSMutableArray* destinationArray = [self.destinationObject mutableArrayValueForKey:relationshipMapping.destinationKeyPath]; + NSMutableArray *destinationArray = [self.destinationObject mutableArrayValueForKey:relationshipMapping.destinationKeyPath]; [destinationArray setArray:destinationObject]; } else if (nsOrderedSetClass && [destinationObject isKindOfClass:nsOrderedSetClass]) { RKLogTrace(@"Mapped NSOrderedSet relationship object from keyPath '%@' to '%@'. Value: %@", relationshipMapping.sourceKeyPath, relationshipMapping.destinationKeyPath, destinationObject); @@ -578,12 +595,12 @@ - (BOOL)applyRelationshipMappings { // One to one relationship RKLogDebug(@"Mapping one to one relationship value at keyPath '%@' to '%@'", relationshipMapping.sourceKeyPath, relationshipMapping.destinationKeyPath); - RKObjectMappingDefinition * mapping = relationshipMapping.mapping; - RKObjectMapping* objectMapping = nil; + RKObjectMappingDefinition *mapping = relationshipMapping.mapping; + RKObjectMapping *objectMapping = nil; if ([mapping isKindOfClass:[RKDynamicObjectMapping class]]) { - objectMapping = [(RKDynamicObjectMapping*)mapping objectMappingForDictionary:value]; + objectMapping = [(RKDynamicObjectMapping *)mapping objectMappingForDictionary:value]; } else if ([mapping isKindOfClass:[RKObjectMapping class]]) { - objectMapping = (RKObjectMapping*)mapping; + objectMapping = (RKObjectMapping *)mapping; } NSAssert(objectMapping, @"Encountered unknown mapping type '%@'", NSStringFromClass([mapping class])); destinationObject = [objectMapping mappableObjectForData:value]; @@ -617,8 +634,9 @@ - (BOOL)applyRelationshipMappings { return appliedMappings; } -- (void)applyNestedMappings { - RKObjectAttributeMapping* attributeMapping = [self.objectMapping attributeMappingForKeyOfNestedDictionary]; +- (void)applyNestedMappings +{ + RKObjectAttributeMapping *attributeMapping = [self.objectMapping attributeMappingForKeyOfNestedDictionary]; if (attributeMapping) { RKLogDebug(@"Found nested mapping definition to attribute '%@'", attributeMapping.destinationKeyPath); id attributeValue = [[self.sourceObject allKeys] lastObject]; @@ -632,7 +650,8 @@ - (void)applyNestedMappings { } } -- (BOOL)performMapping:(NSError**)error { +- (BOOL)performMapping:(NSError **)error +{ RKLogDebug(@"Starting mapping operation..."); RKLogTrace(@"Performing mapping operation: %@", self); @@ -660,7 +679,8 @@ - (BOOL)performMapping:(NSError**)error { return NO; } -- (NSString*)description { +- (NSString *)description +{ return [NSString stringWithFormat:@"RKObjectMappingOperation for '%@' object. Mapping values from object %@ to object %@ with object mapping %@", NSStringFromClass([self.destinationObject class]), self.sourceObject, self.destinationObject, self.objectMapping]; } diff --git a/Code/ObjectMapping/RKObjectMappingProvider.h b/Code/ObjectMapping/RKObjectMappingProvider.h index 7a6cb197ba..acbe109fca 100644 --- a/Code/ObjectMapping/RKObjectMappingProvider.h +++ b/Code/ObjectMapping/RKObjectMappingProvider.h @@ -126,7 +126,7 @@ typedef enum { We might configure a mapping like so: - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[Person class]]; + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[Person class]]; [mapping mapAttributes:@"first_name", @"last_name", nil]; If we want to parse the above JSON and serialize it such that using postObject: or putObject: use the same format, @@ -139,7 +139,7 @@ typedef enum { If you want to manipulate the serialization mapping yourself, you can work with the mapping directly: - RKObjectMapping* serializationMappingForPerson = [personMapping inverseMapping]; + RKObjectMapping *serializationMappingForPerson = [personMapping inverseMapping]; // NOTE: Serialization mapping default to a nil root keyPath and will serialize to a flat dictionary [[RKObjectManager sharedManager].mappingProvider setSerializationMapping:serializationMappingForPerson forClass:[Person class]]; diff --git a/Code/ObjectMapping/RKObjectMappingProvider.m b/Code/ObjectMapping/RKObjectMappingProvider.m index 3bf5d4ecad..98329f7389 100644 --- a/Code/ObjectMapping/RKObjectMappingProvider.m +++ b/Code/ObjectMapping/RKObjectMappingProvider.m @@ -23,20 +23,24 @@ #import "RKOrderedDictionary.h" #import "RKPathMatcher.h" #import "RKObjectMappingProviderContextEntry.h" +#import "RKErrorMessage.h" @implementation RKObjectMappingProvider -+ (RKObjectMappingProvider *)mappingProvider { ++ (RKObjectMappingProvider *)mappingProvider +{ return [[self new] autorelease]; } -+ (RKObjectMappingProvider *)mappingProviderUsingBlock:(void (^)(RKObjectMappingProvider *mappingProvider))block { - RKObjectMappingProvider* mappingProvider = [self mappingProvider]; ++ (RKObjectMappingProvider *)mappingProviderUsingBlock:(void (^)(RKObjectMappingProvider *mappingProvider))block +{ + RKObjectMappingProvider *mappingProvider = [self mappingProvider]; block(mappingProvider); return mappingProvider; } -- (id)init { +- (id)init +{ self = [super init]; if (self) { mappingContexts = [NSMutableDictionary new]; @@ -45,59 +49,75 @@ - (id)init { [self initializeContext:RKObjectMappingProviderContextObjectsByResourcePathPattern withValue:[RKOrderedDictionary dictionary]]; [self initializeContext:RKObjectMappingProviderContextSerialization withValue:[NSMutableDictionary dictionary]]; [self initializeContext:RKObjectMappingProviderContextErrors withValue:[NSNull null]]; + + // Setup default error message mappings + RKObjectMapping *errorMapping = [RKObjectMapping mappingForClass:[RKErrorMessage class]]; + errorMapping.rootKeyPath = @"errors"; + [errorMapping mapKeyPath:@"" toAttribute:@"errorMessage"]; + self.errorMapping = errorMapping; } return self; } -- (void)dealloc { +- (void)dealloc +{ [mappingContexts release]; [super dealloc]; } -- (void)setObjectMapping:(RKObjectMappingDefinition *)objectOrDynamicMapping forKeyPath:(NSString *)keyPath { +- (void)setObjectMapping:(RKObjectMappingDefinition *)objectOrDynamicMapping forKeyPath:(NSString *)keyPath +{ [self setMapping:objectOrDynamicMapping forKeyPath:keyPath context:RKObjectMappingProviderContextObjectsByKeyPath]; } -- (void)removeObjectMappingForKeyPath:(NSString *)keyPath { +- (void)removeObjectMappingForKeyPath:(NSString *)keyPath +{ [self removeMappingForKeyPath:keyPath context:RKObjectMappingProviderContextObjectsByKeyPath]; } -- (RKObjectMappingDefinition *)objectMappingForKeyPath:(NSString *)keyPath { +- (RKObjectMappingDefinition *)objectMappingForKeyPath:(NSString *)keyPath +{ return [self mappingForKeyPath:keyPath context:RKObjectMappingProviderContextObjectsByKeyPath]; } -- (void)setSerializationMapping:(RKObjectMapping *)mapping forClass:(Class)objectClass { +- (void)setSerializationMapping:(RKObjectMapping *)mapping forClass:(Class)objectClass +{ [self setMapping:mapping forKeyPath:NSStringFromClass(objectClass) context:RKObjectMappingProviderContextSerialization]; } -- (RKObjectMapping *)serializationMappingForClass:(Class)objectClass { - return (RKObjectMapping *) [self mappingForKeyPath:NSStringFromClass(objectClass) context:RKObjectMappingProviderContextSerialization]; +- (RKObjectMapping *)serializationMappingForClass:(Class)objectClass +{ + return (RKObjectMapping *)[self mappingForKeyPath:NSStringFromClass(objectClass) context:RKObjectMappingProviderContextSerialization]; } -- (NSDictionary*)objectMappingsByKeyPath { - return [NSDictionary dictionaryWithDictionary:(NSDictionary *) [self valueForContext:RKObjectMappingProviderContextObjectsByKeyPath]]; +- (NSDictionary *)objectMappingsByKeyPath +{ + return [NSDictionary dictionaryWithDictionary:(NSDictionary *)[self valueForContext:RKObjectMappingProviderContextObjectsByKeyPath]]; } -- (void)registerObjectMapping:(RKObjectMapping *)objectMapping withRootKeyPath:(NSString *)keyPath { +- (void)registerObjectMapping:(RKObjectMapping *)objectMapping withRootKeyPath:(NSString *)keyPath +{ // TODO: Should generate logs objectMapping.rootKeyPath = keyPath; [self setMapping:objectMapping forKeyPath:keyPath]; - RKObjectMapping* inverseMapping = [objectMapping inverseMapping]; + RKObjectMapping *inverseMapping = [objectMapping inverseMapping]; inverseMapping.rootKeyPath = keyPath; [self setSerializationMapping:inverseMapping forClass:objectMapping.objectClass]; } -- (void)addObjectMapping:(RKObjectMapping *)objectMapping { +- (void)addObjectMapping:(RKObjectMapping *)objectMapping +{ [self addMapping:objectMapping context:RKObjectMappingProviderContextObjectsByType]; } -- (NSArray *)objectMappingsForClass:(Class)theClass { +- (NSArray *)objectMappingsForClass:(Class)theClass +{ NSMutableArray *mappings = [NSMutableArray array]; NSArray *mappingByType = [self valueForContext:RKObjectMappingProviderContextObjectsByType]; NSArray *mappingByKeyPath = [[self valueForContext:RKObjectMappingProviderContextObjectsByKeyPath] allValues]; NSArray *mappingsToSearch = [[NSArray arrayWithArray:mappingByType] arrayByAddingObjectsFromArray:mappingByKeyPath]; for (RKObjectMappingDefinition *candidateMapping in mappingsToSearch) { - if ( ![candidateMapping respondsToSelector:@selector(objectClass)] || [mappings containsObject:candidateMapping]) + if (![candidateMapping respondsToSelector:@selector(objectClass)] || [mappings containsObject:candidateMapping]) continue; Class mappedClass = [candidateMapping performSelector:@selector(objectClass)]; if (mappedClass && [NSStringFromClass(mappedClass) isEqualToString:NSStringFromClass(theClass)]) { @@ -107,18 +127,21 @@ - (NSArray *)objectMappingsForClass:(Class)theClass { return [NSArray arrayWithArray:mappings]; } -- (RKObjectMapping *)objectMappingForClass:(Class)theClass { - NSArray* objectMappings = [self objectMappingsForClass:theClass]; +- (RKObjectMapping *)objectMappingForClass:(Class)theClass +{ + NSArray *objectMappings = [self objectMappingsForClass:theClass]; return ([objectMappings count] > 0) ? [objectMappings objectAtIndex:0] : nil; } #pragma mark - Error Mappings -- (RKObjectMapping *)errorMapping { - return (RKObjectMapping *) [self mappingForContext:RKObjectMappingProviderContextErrors]; +- (RKObjectMapping *)errorMapping +{ + return (RKObjectMapping *)[self mappingForContext:RKObjectMappingProviderContextErrors]; } -- (void)setErrorMapping:(RKObjectMapping *)errorMapping { +- (void)setErrorMapping:(RKObjectMapping *)errorMapping +{ if (errorMapping) { [self setMapping:errorMapping context:RKObjectMappingProviderContextErrors]; } @@ -126,58 +149,70 @@ - (void)setErrorMapping:(RKObjectMapping *)errorMapping { #pragma mark - Pagination Mapping -- (RKObjectMapping *)paginationMapping { - return (RKObjectMapping *) [self mappingForContext:RKObjectMappingProviderContextPagination]; +- (RKObjectMapping *)paginationMapping +{ + return (RKObjectMapping *)[self mappingForContext:RKObjectMappingProviderContextPagination]; } -- (void)setPaginationMapping:(RKObjectMapping *)paginationMapping { +- (void)setPaginationMapping:(RKObjectMapping *)paginationMapping +{ [self setMapping:paginationMapping context:RKObjectMappingProviderContextPagination]; } -- (void)setObjectMapping:(RKObjectMappingDefinition *)objectMapping forResourcePathPattern:(NSString *)resourcePath { +- (void)setObjectMapping:(RKObjectMappingDefinition *)objectMapping forResourcePathPattern:(NSString *)resourcePath +{ [self setMapping:objectMapping forPattern:resourcePath context:RKObjectMappingProviderContextObjectsByResourcePathPattern]; } -- (RKObjectMappingDefinition *)objectMappingForResourcePath:(NSString *)resourcePath { +- (RKObjectMappingDefinition *)objectMappingForResourcePath:(NSString *)resourcePath +{ return [self mappingForPatternMatchingString:resourcePath context:RKObjectMappingProviderContextObjectsByResourcePathPattern]; } -- (void)setEntry:(RKObjectMappingProviderContextEntry *)entry forResourcePathPattern:(NSString *)resourcePath { +- (void)setEntry:(RKObjectMappingProviderContextEntry *)entry forResourcePathPattern:(NSString *)resourcePath +{ [self setEntry:entry forPattern:resourcePath context:RKObjectMappingProviderContextObjectsByResourcePathPattern]; } -- (RKObjectMappingProviderContextEntry *)entryForResourcePath:(NSString *)resourcePath { +- (RKObjectMappingProviderContextEntry *)entryForResourcePath:(NSString *)resourcePath +{ return [self entryForPatternMatchingString:resourcePath context:RKObjectMappingProviderContextObjectsByResourcePathPattern]; } #pragma mark - Mapping Context Primitives -- (void)initializeContext:(RKObjectMappingProviderContext)context withValue:(id)value { +- (void)initializeContext:(RKObjectMappingProviderContext)context withValue:(id)value +{ NSAssert([self valueForContext:context] == nil, @"Attempt to reinitialized an existing mapping provider context."); [self setValue:value forContext:context]; } -- (id)valueForContext:(RKObjectMappingProviderContext)context { +- (id)valueForContext:(RKObjectMappingProviderContext)context +{ NSNumber *contextNumber = [NSNumber numberWithInteger:context]; return [mappingContexts objectForKey:contextNumber]; } -- (void)setValue:(id)value forContext:(RKObjectMappingProviderContext)context { +- (void)setValue:(id)value forContext:(RKObjectMappingProviderContext)context +{ NSNumber *contextNumber = [NSNumber numberWithInteger:context]; [mappingContexts setObject:value forKey:contextNumber]; } -- (void)assertStorageForContext:(RKObjectMappingProviderContext)context isKindOfClass:(Class)theClass { +- (void)assertStorageForContext:(RKObjectMappingProviderContext)context isKindOfClass:(Class)theClass +{ id contextValue = [self valueForContext:context]; NSAssert([contextValue isKindOfClass:theClass], @"Storage type mismatch for context %d: expected a %@, got %@.", context, theClass, [contextValue class]); } -- (void)setMapping:(RKObjectMappingDefinition *)mapping context:(RKObjectMappingProviderContext)context { +- (void)setMapping:(RKObjectMappingDefinition *)mapping context:(RKObjectMappingProviderContext)context +{ NSNumber *contextNumber = [NSNumber numberWithInteger:context]; [mappingContexts setObject:mapping forKey:contextNumber]; } -- (RKObjectMappingDefinition *)mappingForContext:(RKObjectMappingProviderContext)context { +- (RKObjectMappingDefinition *)mappingForContext:(RKObjectMappingProviderContext)context +{ id contextValue = [self valueForContext:context]; if ([contextValue isEqual:[NSNull null]]) return nil; Class class = [RKObjectMappingDefinition class]; @@ -185,7 +220,8 @@ - (RKObjectMappingDefinition *)mappingForContext:(RKObjectMappingProviderContext return contextValue; } -- (NSArray *)mappingsForContext:(RKObjectMappingProviderContext)context { +- (NSArray *)mappingsForContext:(RKObjectMappingProviderContext)context +{ id contextValue = [self valueForContext:context]; if (contextValue == nil) return [NSArray array]; [self assertStorageForContext:context isKindOfClass:[NSArray class]]; @@ -193,7 +229,8 @@ - (NSArray *)mappingsForContext:(RKObjectMappingProviderContext)context { return [NSArray arrayWithArray:contextValue]; } -- (void)addMapping:(RKObjectMappingDefinition *)mapping context:(RKObjectMappingProviderContext)context { +- (void)addMapping:(RKObjectMappingDefinition *)mapping context:(RKObjectMappingProviderContext)context +{ NSMutableArray *contextValue = [self valueForContext:context]; if (contextValue == nil) { contextValue = [NSMutableArray arrayWithCapacity:1]; @@ -203,7 +240,8 @@ - (void)addMapping:(RKObjectMappingDefinition *)mapping context:(RKObjectMapping [contextValue addObject:mapping]; } -- (void)removeMapping:(RKObjectMappingDefinition *)mapping context:(RKObjectMappingProviderContext)context { +- (void)removeMapping:(RKObjectMappingDefinition *)mapping context:(RKObjectMappingProviderContext)context +{ NSMutableArray *contextValue = [self valueForContext:context]; NSAssert(contextValue, @"Attempted to remove mapping from undefined context: %d", context); [self assertStorageForContext:context isKindOfClass:[NSArray class]]; @@ -211,14 +249,16 @@ - (void)removeMapping:(RKObjectMappingDefinition *)mapping context:(RKObjectMapp [contextValue removeObject:mapping]; } -- (RKObjectMappingDefinition *)mappingForKeyPath:(NSString *)keyPath context:(RKObjectMappingProviderContext)context { +- (RKObjectMappingDefinition *)mappingForKeyPath:(NSString *)keyPath context:(RKObjectMappingProviderContext)context +{ NSMutableDictionary *contextValue = [self valueForContext:context]; NSAssert(contextValue, @"Attempted to retrieve mapping from undefined context: %d", context); [self assertStorageForContext:context isKindOfClass:[NSDictionary class]]; return [contextValue valueForKey:keyPath]; } -- (void)setMapping:(RKObjectMappingDefinition *)mapping forKeyPath:(NSString *)keyPath context:(RKObjectMappingProviderContext)context { +- (void)setMapping:(RKObjectMappingDefinition *)mapping forKeyPath:(NSString *)keyPath context:(RKObjectMappingProviderContext)context +{ NSMutableDictionary *contextValue = [self valueForContext:context]; if (contextValue == nil) { contextValue = [NSMutableDictionary dictionary]; @@ -228,13 +268,15 @@ - (void)setMapping:(RKObjectMappingDefinition *)mapping forKeyPath:(NSString *)k [contextValue setValue:mapping forKey:keyPath]; } -- (void)removeMappingForKeyPath:(NSString *)keyPath context:(RKObjectMappingProviderContext)context { +- (void)removeMappingForKeyPath:(NSString *)keyPath context:(RKObjectMappingProviderContext)context +{ NSMutableDictionary *contextValue = [self valueForContext:context]; [self assertStorageForContext:context isKindOfClass:[NSDictionary class]]; [contextValue removeObjectForKey:keyPath]; } -- (void)setMapping:(RKObjectMappingDefinition *)mapping forPattern:(NSString *)pattern atIndex:(NSUInteger)index context:(RKObjectMappingProviderContext)context { +- (void)setMapping:(RKObjectMappingDefinition *)mapping forPattern:(NSString *)pattern atIndex:(NSUInteger)index context:(RKObjectMappingProviderContext)context +{ RKOrderedDictionary *contextValue = [self valueForContext:context]; if (contextValue == nil) { contextValue = [RKOrderedDictionary dictionary]; @@ -246,7 +288,8 @@ - (void)setMapping:(RKObjectMappingDefinition *)mapping forPattern:(NSString *)p atIndex:index]; } -- (void)setMapping:(RKObjectMappingDefinition *)mapping forPattern:(NSString *)pattern context:(RKObjectMappingProviderContext)context { +- (void)setMapping:(RKObjectMappingDefinition *)mapping forPattern:(NSString *)pattern context:(RKObjectMappingProviderContext)context +{ RKOrderedDictionary *contextValue = [self valueForContext:context]; if (contextValue == nil) { contextValue = [RKOrderedDictionary dictionary]; @@ -257,7 +300,8 @@ - (void)setMapping:(RKObjectMappingDefinition *)mapping forPattern:(NSString *)p forKey:pattern]; } -- (RKObjectMappingDefinition *)mappingForPatternMatchingString:(NSString *)string context:(RKObjectMappingProviderContext)context { +- (RKObjectMappingDefinition *)mappingForPatternMatchingString:(NSString *)string context:(RKObjectMappingProviderContext)context +{ NSAssert(string, @"Cannot look up mapping matching nil pattern string."); RKOrderedDictionary *contextValue = [self valueForContext:context]; NSAssert(contextValue, @"Attempted to retrieve mapping from undefined context: %d", context); @@ -272,7 +316,8 @@ - (RKObjectMappingDefinition *)mappingForPatternMatchingString:(NSString *)strin return nil; } -- (void)setEntry:(RKObjectMappingProviderContextEntry *)entry forPattern:(NSString *)pattern context:(RKObjectMappingProviderContext)context { +- (void)setEntry:(RKObjectMappingProviderContextEntry *)entry forPattern:(NSString *)pattern context:(RKObjectMappingProviderContext)context +{ RKOrderedDictionary *contextValue = [self valueForContext:context]; if (contextValue == nil) { contextValue = [RKOrderedDictionary dictionary]; @@ -283,7 +328,8 @@ - (void)setEntry:(RKObjectMappingProviderContextEntry *)entry forPattern:(NSStri forKey:pattern]; } -- (RKObjectMappingProviderContextEntry *)entryForPatternMatchingString:(NSString *)string context:(RKObjectMappingProviderContext)context { +- (RKObjectMappingProviderContextEntry *)entryForPatternMatchingString:(NSString *)string context:(RKObjectMappingProviderContext)context +{ RKOrderedDictionary *contextValue = [self valueForContext:context]; NSAssert(contextValue, @"Attempted to retrieve mapping from undefined context: %d", context); for (NSString *pattern in contextValue) { @@ -298,32 +344,39 @@ - (RKObjectMappingProviderContextEntry *)entryForPatternMatchingString:(NSString #pragma mark - Aliases -+ (RKObjectMappingProvider *)objectMappingProvider { ++ (RKObjectMappingProvider *)objectMappingProvider +{ return [self mappingProvider]; } -- (RKObjectMapping *)mappingForKeyPath:(NSString *)keyPath { - return (RKObjectMapping *) [self objectMappingForKeyPath:keyPath]; +- (RKObjectMapping *)mappingForKeyPath:(NSString *)keyPath +{ + return (RKObjectMapping *)[self objectMappingForKeyPath:keyPath]; } -- (void)setMapping:(RKObjectMapping *)mapping forKeyPath:(NSString *)keyPath { +- (void)setMapping:(RKObjectMapping *)mapping forKeyPath:(NSString *)keyPath +{ [self setObjectMapping:mapping forKeyPath:keyPath]; } -- (NSDictionary *)mappingsByKeyPath { +- (NSDictionary *)mappingsByKeyPath +{ return [self objectMappingsByKeyPath]; } -- (void)registerMapping:(RKObjectMapping *)objectMapping withRootKeyPath:(NSString *)keyPath { +- (void)registerMapping:(RKObjectMapping *)objectMapping withRootKeyPath:(NSString *)keyPath +{ return [self registerObjectMapping:objectMapping withRootKeyPath:keyPath]; } -- (void)removeMappingForKeyPath:(NSString *)keyPath { +- (void)removeMappingForKeyPath:(NSString *)keyPath +{ [self removeObjectMappingForKeyPath:keyPath]; } // Deprecated -+ (id)mappingProviderWithBlock:(void (^)(RKObjectMappingProvider*))block { ++ (id)mappingProviderWithBlock:(void (^)(RKObjectMappingProvider *))block +{ return [self mappingProviderUsingBlock:block]; } diff --git a/Code/ObjectMapping/RKObjectMappingProviderContextEntry.m b/Code/ObjectMapping/RKObjectMappingProviderContextEntry.m index da328f183d..6e8ba5bbeb 100644 --- a/Code/ObjectMapping/RKObjectMappingProviderContextEntry.m +++ b/Code/ObjectMapping/RKObjectMappingProviderContextEntry.m @@ -13,7 +13,8 @@ @implementation RKObjectMappingProviderContextEntry @synthesize mapping = _mapping; @synthesize userData = _userData; -- (id)init { +- (id)init +{ self = [super init]; if (self) { _mapping = nil; @@ -22,7 +23,8 @@ - (id)init { return self; } -- (void)dealloc { +- (void)dealloc +{ [_mapping release]; _mapping = nil; [_userData release]; @@ -30,7 +32,8 @@ - (void)dealloc { [super dealloc]; } -- (BOOL)isEqual:(id)object { +- (BOOL)isEqual:(id)object +{ if ([object isKindOfClass:[RKObjectMappingProviderContextEntry class]]) { RKObjectMappingProviderContextEntry *entry = (RKObjectMappingProviderContextEntry *)object; return ([self.mapping isEqual:entry.mapping] && (self.userData == entry.userData)); @@ -38,20 +41,23 @@ - (BOOL)isEqual:(id)object { return NO; } -- (NSUInteger)hash { +- (NSUInteger)hash +{ int prime = 31; int result = 1; - result = prime * [self.userData hash]? [self.mapping hash] : [self.userData hash]; + result = prime *[self.userData hash] ? [self.mapping hash] : [self.userData hash]; return result; } -+ (RKObjectMappingProviderContextEntry *)contextEntryWithMapping:(RKObjectMappingDefinition *)mapping { ++ (RKObjectMappingProviderContextEntry *)contextEntryWithMapping:(RKObjectMappingDefinition *)mapping +{ RKObjectMappingProviderContextEntry *contextEntry = [[[RKObjectMappingProviderContextEntry alloc] init] autorelease]; contextEntry.mapping = mapping; return contextEntry; } -+ (RKObjectMappingProviderContextEntry *)contextEntryWithMapping:(RKObjectMappingDefinition *)mapping userData:(id)userData { ++ (RKObjectMappingProviderContextEntry *)contextEntryWithMapping:(RKObjectMappingDefinition *)mapping userData:(id)userData +{ RKObjectMappingProviderContextEntry *contextEntry = [RKObjectMappingProviderContextEntry contextEntryWithMapping:mapping]; contextEntry.userData = userData; return contextEntry; diff --git a/Code/ObjectMapping/RKObjectMappingResult.h b/Code/ObjectMapping/RKObjectMappingResult.h index 07acbbf698..30390fbf6c 100644 --- a/Code/ObjectMapping/RKObjectMappingResult.h +++ b/Code/ObjectMapping/RKObjectMappingResult.h @@ -26,14 +26,14 @@ } - (id)initWithDictionary:(id)dictionary; -+ (RKObjectMappingResult*)mappingResultWithDictionary:(NSDictionary*)keyPathToMappedObjects; ++ (RKObjectMappingResult *)mappingResultWithDictionary:(NSDictionary *)keyPathToMappedObjects; /** Return the mapping result as a dictionary */ -- (NSDictionary*)asDictionary; +- (NSDictionary *)asDictionary; - (id)asObject; -- (NSArray*)asCollection; -- (NSError*)asError; +- (NSArray *)asCollection; +- (NSError *)asError; @end diff --git a/Code/ObjectMapping/RKObjectMappingResult.m b/Code/ObjectMapping/RKObjectMappingResult.m index 02061f3919..b4924939ef 100644 --- a/Code/ObjectMapping/RKObjectMappingResult.m +++ b/Code/ObjectMapping/RKObjectMappingResult.m @@ -24,7 +24,8 @@ @implementation RKObjectMappingResult -- (id)initWithDictionary:(id)dictionary { +- (id)initWithDictionary:(id)dictionary +{ self = [self init]; if (self) { _keyPathToMappedObjects = [dictionary retain]; @@ -33,22 +34,26 @@ - (id)initWithDictionary:(id)dictionary { return self; } -- (void)dealloc { +- (void)dealloc +{ [_keyPathToMappedObjects release]; [super dealloc]; } -+ (RKObjectMappingResult*)mappingResultWithDictionary:(NSDictionary*)keyPathToMappedObjects { ++ (RKObjectMappingResult *)mappingResultWithDictionary:(NSDictionary *)keyPathToMappedObjects +{ return [[[self alloc] initWithDictionary:keyPathToMappedObjects] autorelease]; } -- (NSDictionary*)asDictionary { +- (NSDictionary *)asDictionary +{ return _keyPathToMappedObjects; } -- (NSArray*)asCollection { +- (NSArray *)asCollection +{ // Flatten results down into a single array - NSMutableArray* collection = [NSMutableArray array]; + NSMutableArray *collection = [NSMutableArray array]; for (id object in [_keyPathToMappedObjects allValues]) { // We don't want to strip the keys off of a mapped dictionary result @@ -62,29 +67,31 @@ - (NSArray*)asCollection { return collection; } -- (id)asObject { - NSArray* collection = [self asCollection]; +- (id)asObject +{ + NSArray *collection = [self asCollection]; NSUInteger count = [collection count]; if (count == 0) { return nil; } - if (count > 1) RKLogWarning(@"Coerced object mapping result containing %lu objects into singular result.", (unsigned long) count); + if (count > 1) RKLogWarning(@"Coerced object mapping result containing %lu objects into singular result.", (unsigned long)count); return [collection objectAtIndex:0]; } -- (NSError*)asError { - NSArray* collection = [self asCollection]; - NSString* description = nil; +- (NSError *)asError +{ + NSArray *collection = [self asCollection]; + NSString *description = nil; if ([collection count] > 0) { description = [[collection valueForKeyPath:@"description"] componentsJoinedByString:@", "]; } else { RKLogWarning(@"Expected mapping result to contain at least one object to construct an error"); } - NSDictionary* userInfo = [NSDictionary dictionaryWithObjectsAndKeys:collection, RKObjectMapperErrorObjectsKey, + NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:collection, RKObjectMapperErrorObjectsKey, description, NSLocalizedDescriptionKey, nil]; - NSError* error = [NSError errorWithDomain:RKErrorDomain code:RKObjectMapperErrorFromMappingResult userInfo:userInfo]; + NSError *error = [NSError errorWithDomain:RKErrorDomain code:RKObjectMapperErrorFromMappingResult userInfo:userInfo]; return error; } diff --git a/Code/ObjectMapping/RKObjectPaginator.m b/Code/ObjectMapping/RKObjectPaginator.m index 71e10b196f..892d9b731d 100644 --- a/Code/ObjectMapping/RKObjectPaginator.m +++ b/Code/ObjectMapping/RKObjectPaginator.m @@ -47,11 +47,13 @@ @implementation RKObjectPaginator @synthesize onDidLoadObjectsForPage; @synthesize onDidFailWithError; -+ (id)paginatorWithPatternURL:(RKURL *)aPatternURL mappingProvider:(RKObjectMappingProvider *)aMappingProvider { ++ (id)paginatorWithPatternURL:(RKURL *)aPatternURL mappingProvider:(RKObjectMappingProvider *)aMappingProvider +{ return [[[self alloc] initWithPatternURL:aPatternURL mappingProvider:aMappingProvider] autorelease]; } -- (id)initWithPatternURL:(RKURL *)aPatternURL mappingProvider:(RKObjectMappingProvider *)aMappingProvider { +- (id)initWithPatternURL:(RKURL *)aPatternURL mappingProvider:(RKObjectMappingProvider *)aMappingProvider +{ self = [super init]; if (self) { patternURL = [aPatternURL copy]; @@ -66,7 +68,8 @@ - (id)initWithPatternURL:(RKURL *)aPatternURL mappingProvider:(RKObjectMappingPr return self; } -- (void)dealloc { +- (void)dealloc +{ delegate = nil; configurationDelegate = nil; objectLoader.delegate = nil; @@ -88,53 +91,63 @@ - (void)dealloc { [super dealloc]; } -- (RKObjectMapping *)paginationMapping { +- (RKObjectMapping *)paginationMapping +{ return [mappingProvider paginationMapping]; } -- (RKURL *)URL { +- (RKURL *)URL +{ return [patternURL URLByInterpolatingResourcePathWithObject:self]; } // Private. Public consumers can rely on isLoaded -- (BOOL)hasCurrentPage { +- (BOOL)hasCurrentPage +{ return currentPage != NSUIntegerMax; } -- (BOOL)hasPageCount { +- (BOOL)hasPageCount +{ return pageCount != NSUIntegerMax; } -- (BOOL)hasObjectCount { +- (BOOL)hasObjectCount +{ return objectCount != NSUIntegerMax; } -- (NSUInteger)currentPage { +- (NSUInteger)currentPage +{ // Referenced during initial load, so we don't rely on isLoaded. NSAssert([self hasCurrentPage], @"Current page has not been initialized."); return currentPage; } -- (NSUInteger)pageCount { +- (NSUInteger)pageCount +{ NSAssert([self hasPageCount], @"Page count not available."); return pageCount; } -- (BOOL)hasNextPage { +- (BOOL)hasNextPage +{ NSAssert(self.isLoaded, @"Cannot determine hasNextPage: paginator is not loaded."); NSAssert([self hasPageCount], @"Cannot determine hasNextPage: page count is not known."); return self.currentPage < self.pageCount; } -- (BOOL)hasPreviousPage { +- (BOOL)hasPreviousPage +{ NSAssert(self.isLoaded, @"Cannot determine hasPreviousPage: paginator is not loaded."); return self.currentPage > 1; } #pragma mark - RKObjectLoaderDelegate methods -- (void)objectLoader:(RKObjectLoader *)objectLoader didLoadObjects:(NSArray *)objects { +- (void)objectLoader:(RKObjectLoader *)objectLoader didLoadObjects:(NSArray *)objects +{ self.objectLoader = nil; loaded = YES; RKLogInfo(@"Loaded objects: %@", objects); @@ -157,7 +170,8 @@ - (void)objectLoader:(RKObjectLoader *)objectLoader didLoadObjects:(NSArray *)ob } } -- (void)objectLoader:(RKObjectLoader *)objectLoader didFailWithError:(NSError *)error { +- (void)objectLoader:(RKObjectLoader *)objectLoader didFailWithError:(NSError *)error +{ RKLogError(@"Paginator error %@", error); [self.delegate paginator:self didFailWithError:error objectLoader:self.objectLoader]; if (self.onDidFailWithError) { @@ -166,7 +180,8 @@ - (void)objectLoader:(RKObjectLoader *)objectLoader didFailWithError:(NSError *) self.objectLoader = nil; } -- (void)objectLoader:(RKObjectLoader *)loader willMapData:(inout id *)mappableData { +- (void)objectLoader:(RKObjectLoader *)loader willMapData:(inout id *)mappableData +{ NSError *error = nil; RKObjectMappingOperation *mappingOperation = [RKObjectMappingOperation mappingOperationFromObject:*mappableData toObject:self withMapping:[self paginationMapping]]; BOOL success = [mappingOperation performMapping:&error]; @@ -176,7 +191,7 @@ - (void)objectLoader:(RKObjectLoader *)loader willMapData:(inout id *)mappableDa } else if (self.perPage && [self hasObjectCount]) { float objectCountFloat = self.objectCount; pageCount = ceilf(objectCountFloat / self.perPage); - RKLogInfo(@"Paginator objectCount: %ld pageCount: %ld", (long) self.objectCount, (long) self.pageCount); + RKLogInfo(@"Paginator objectCount: %ld pageCount: %ld", (long)self.objectCount, (long)self.pageCount); } else { NSAssert(NO, @"Paginator perPage set is 0."); RKLogError(@"Paginator perPage set is 0."); @@ -185,15 +200,18 @@ - (void)objectLoader:(RKObjectLoader *)loader willMapData:(inout id *)mappableDa #pragma mark - Action methods -- (void)loadNextPage { +- (void)loadNextPage +{ [self loadPage:currentPage + 1]; } -- (void)loadPreviousPage { +- (void)loadPreviousPage +{ [self loadPage:currentPage - 1]; } -- (void)loadPage:(NSUInteger)pageNumber { +- (void)loadPage:(NSUInteger)pageNumber +{ NSAssert(self.mappingProvider, @"Cannot perform a load with a nil mappingProvider."); NSAssert(! objectLoader, @"Cannot perform a load while one is already in progress."); currentPage = pageNumber; diff --git a/Code/ObjectMapping/RKObjectPropertyInspector.h b/Code/ObjectMapping/RKObjectPropertyInspector.h index 1008a418e6..4749439ecd 100644 --- a/Code/ObjectMapping/RKObjectPropertyInspector.h +++ b/Code/ObjectMapping/RKObjectPropertyInspector.h @@ -23,10 +23,10 @@ @class NSEntityDescription; @interface RKObjectPropertyInspector : NSObject { - NSMutableDictionary* _cachedPropertyNamesAndTypes; + NSMutableDictionary *_cachedPropertyNamesAndTypes; } -+ (RKObjectPropertyInspector*)sharedInspector; ++ (RKObjectPropertyInspector *)sharedInspector; /** * Returns a dictionary of names and types for the properties of a given class @@ -36,7 +36,7 @@ /** Returns the Class type of the specified property on the object class */ -- (Class)typeForProperty:(NSString*)propertyName ofClass:(Class)objectClass; +- (Class)typeForProperty:(NSString *)propertyName ofClass:(Class)objectClass; /** Returns the name of a property when provided the name of a property obtained diff --git a/Code/ObjectMapping/RKObjectPropertyInspector.m b/Code/ObjectMapping/RKObjectPropertyInspector.m index 30f501f6f8..03c0c4027e 100644 --- a/Code/ObjectMapping/RKObjectPropertyInspector.m +++ b/Code/ObjectMapping/RKObjectPropertyInspector.m @@ -26,11 +26,12 @@ #undef RKLogComponent #define RKLogComponent lcl_cRestKitObjectMapping -static RKObjectPropertyInspector* sharedInspector = nil; +static RKObjectPropertyInspector *sharedInspector = nil; @implementation RKObjectPropertyInspector -+ (RKObjectPropertyInspector*)sharedInspector { ++ (RKObjectPropertyInspector *)sharedInspector +{ if (sharedInspector == nil) { sharedInspector = [RKObjectPropertyInspector new]; } @@ -38,7 +39,8 @@ + (RKObjectPropertyInspector*)sharedInspector { return sharedInspector; } -- (id)init { +- (id)init +{ if ((self = [super init])) { _cachedPropertyNamesAndTypes = [[NSMutableDictionary alloc] init]; } @@ -46,18 +48,20 @@ - (id)init { return self; } -- (void)dealloc { +- (void)dealloc +{ [_cachedPropertyNamesAndTypes release]; [super dealloc]; } -+ (NSString*)propertyTypeFromAttributeString:(NSString*)attributeString { ++ (NSString *)propertyTypeFromAttributeString:(NSString *)attributeString +{ NSString *type = [NSString string]; NSScanner *typeScanner = [NSScanner scannerWithString:attributeString]; [typeScanner scanUpToCharactersFromSet:[NSCharacterSet characterSetWithCharactersInString:@"@"] intoString:NULL]; // we are not dealing with an object - if([typeScanner isAtEnd]) { + if ([typeScanner isAtEnd]) { return @"NULL"; } [typeScanner scanCharactersFromSet:[NSCharacterSet characterSetWithCharactersInString:@"\"@"] intoString:NULL]; @@ -66,8 +70,9 @@ + (NSString*)propertyTypeFromAttributeString:(NSString*)attributeString { return type; } -- (NSDictionary *)propertyNamesAndTypesForClass:(Class)theClass { - NSMutableDictionary* propertyNames = [_cachedPropertyNamesAndTypes objectForKey:theClass]; +- (NSDictionary *)propertyNamesAndTypesForClass:(Class)theClass +{ + NSMutableDictionary *propertyNames = [_cachedPropertyNamesAndTypes objectForKey:theClass]; if (propertyNames) { return propertyNames; } @@ -86,12 +91,12 @@ - (NSDictionary *)propertyNamesAndTypesForClass:(Class)theClass { for (i = 0; i < outCount; i++) { // property_getAttributes() returns everything we need to implement this... // See: http://developer.apple.com/mac/library/DOCUMENTATION/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtPropertyIntrospection.html#//apple_ref/doc/uid/TP40008048-CH101-SW5 - objc_property_t* prop = propList + i; - NSString* attributeString = [NSString stringWithCString:property_getAttributes(*prop) encoding:NSUTF8StringEncoding]; + objc_property_t *prop = propList + i; + NSString *attributeString = [NSString stringWithCString:property_getAttributes(*prop) encoding:NSUTF8StringEncoding]; propName = [NSString stringWithCString:property_getName(*prop) encoding:NSUTF8StringEncoding]; if (![propName isEqualToString:@"_mapkit_hasPanoramaID"]) { - const char* className = [[RKObjectPropertyInspector propertyTypeFromAttributeString:attributeString] cStringUsingEncoding:NSUTF8StringEncoding]; + const char *className = [[RKObjectPropertyInspector propertyTypeFromAttributeString:attributeString] cStringUsingEncoding:NSUTF8StringEncoding]; Class aClass = objc_getClass(className); if (aClass) { [propertyNames setObject:aClass forKey:propName]; @@ -108,8 +113,9 @@ - (NSDictionary *)propertyNamesAndTypesForClass:(Class)theClass { return propertyNames; } -- (Class)typeForProperty:(NSString*)propertyName ofClass:(Class)objectClass { - NSDictionary* dictionary = [self propertyNamesAndTypesForClass:objectClass]; +- (Class)typeForProperty:(NSString *)propertyName ofClass:(Class)objectClass +{ + NSDictionary *dictionary = [self propertyNamesAndTypesForClass:objectClass]; return [dictionary objectForKey:propertyName]; } diff --git a/Code/ObjectMapping/RKObjectRelationshipMapping.h b/Code/ObjectMapping/RKObjectRelationshipMapping.h index e2b4c26a1b..6eb11a42c6 100644 --- a/Code/ObjectMapping/RKObjectRelationshipMapping.h +++ b/Code/ObjectMapping/RKObjectRelationshipMapping.h @@ -24,16 +24,13 @@ @class RKObjectmapping; -@interface RKObjectRelationshipMapping : RKObjectAttributeMapping { - RKObjectMappingDefinition * _mapping; - BOOL _reversible; -} +@interface RKObjectRelationshipMapping : RKObjectAttributeMapping -@property (nonatomic, retain) RKObjectMappingDefinition * mapping; +@property (nonatomic, retain) RKObjectMappingDefinition *mapping; @property (nonatomic, assign) BOOL reversible; -+ (RKObjectRelationshipMapping*)mappingFromKeyPath:(NSString*)sourceKeyPath toKeyPath:(NSString*)destinationKeyPath withMapping:(RKObjectMappingDefinition *)objectOrDynamicMapping; ++ (RKObjectRelationshipMapping *)mappingFromKeyPath:(NSString *)sourceKeyPath toKeyPath:(NSString *)destinationKeyPath withMapping:(RKObjectMappingDefinition *)objectOrDynamicMapping; -+ (RKObjectRelationshipMapping*)mappingFromKeyPath:(NSString*)sourceKeyPath toKeyPath:(NSString*)destinationKeyPath withMapping:(RKObjectMappingDefinition *)objectOrDynamicMapping reversible:(BOOL)reversible; ++ (RKObjectRelationshipMapping *)mappingFromKeyPath:(NSString *)sourceKeyPath toKeyPath:(NSString *)destinationKeyPath withMapping:(RKObjectMappingDefinition *)objectOrDynamicMapping reversible:(BOOL)reversible; @end diff --git a/Code/ObjectMapping/RKObjectRelationshipMapping.m b/Code/ObjectMapping/RKObjectRelationshipMapping.m index 555ea7eb8b..f9ed9328fe 100644 --- a/Code/ObjectMapping/RKObjectRelationshipMapping.m +++ b/Code/ObjectMapping/RKObjectRelationshipMapping.m @@ -25,25 +25,29 @@ @implementation RKObjectRelationshipMapping @synthesize mapping = _mapping; @synthesize reversible = _reversible; -+ (RKObjectRelationshipMapping*)mappingFromKeyPath:(NSString*)sourceKeyPath toKeyPath:(NSString*)destinationKeyPath withMapping:(RKObjectMappingDefinition *)objectOrDynamicMapping reversible:(BOOL)reversible { - RKObjectRelationshipMapping* relationshipMapping = (RKObjectRelationshipMapping*) [self mappingFromKeyPath:sourceKeyPath toKeyPath:destinationKeyPath]; ++ (RKObjectRelationshipMapping *)mappingFromKeyPath:(NSString *)sourceKeyPath toKeyPath:(NSString *)destinationKeyPath withMapping:(RKObjectMappingDefinition *)objectOrDynamicMapping reversible:(BOOL)reversible +{ + RKObjectRelationshipMapping *relationshipMapping = (RKObjectRelationshipMapping *)[self mappingFromKeyPath:sourceKeyPath toKeyPath:destinationKeyPath]; relationshipMapping.reversible = reversible; relationshipMapping.mapping = objectOrDynamicMapping; return relationshipMapping; } -+ (RKObjectRelationshipMapping*)mappingFromKeyPath:(NSString*)sourceKeyPath toKeyPath:(NSString*)destinationKeyPath withMapping:(RKObjectMappingDefinition *)objectOrDynamicMapping { ++ (RKObjectRelationshipMapping *)mappingFromKeyPath:(NSString *)sourceKeyPath toKeyPath:(NSString *)destinationKeyPath withMapping:(RKObjectMappingDefinition *)objectOrDynamicMapping +{ return [self mappingFromKeyPath:sourceKeyPath toKeyPath:destinationKeyPath withMapping:objectOrDynamicMapping reversible:YES]; } -- (id)copyWithZone:(NSZone *)zone { - RKObjectRelationshipMapping* copy = [super copyWithZone:zone]; +- (id)copyWithZone:(NSZone *)zone +{ + RKObjectRelationshipMapping *copy = [super copyWithZone:zone]; copy.mapping = self.mapping; copy.reversible = self.reversible; return copy; } -- (void)dealloc { +- (void)dealloc +{ [_mapping release]; [super dealloc]; } diff --git a/Code/ObjectMapping/RKObjectRouter.h b/Code/ObjectMapping/RKObjectRouter.h index a340266ceb..73900a3d25 100644 --- a/Code/ObjectMapping/RKObjectRouter.h +++ b/Code/ObjectMapping/RKObjectRouter.h @@ -31,14 +31,14 @@ * the resourcePath using a single colon delimiter, such as /users/:userID */ @interface RKObjectRouter : NSObject { - NSMutableDictionary* _routes; + NSMutableDictionary *_routes; } /** * Register a mapping from an object class to a resource path. This resourcePath can be static * (i.e. /this/is/the/path) or dynamic (i.e. /users/:userID/:username). Dynamic routes are * evaluated against the object being routed using Key-Value coding and coerced into a string. - * *NOTE* - The pattern matcher fully supports KVM, so /:key1.otherKey normally resolves as it + * *NOTE *- The pattern matcher fully supports KVM, so /:key1.otherKey normally resolves as it * would in any other KVM situation, ... otherKey is a sub-key on a the object represented by * key1. This presents a problem in situations where you might want to build a pattern like * /:filename.json, where the dot isn't intended as a sub-key on the dynamic "filename", but @@ -46,13 +46,13 @@ * dot with two backslashes, like so: /:filename\\.json * @see RKPathMatcher */ -- (void)routeClass:(Class)objectClass toResourcePathPattern:(NSString*)resourcePathPattern; +- (void)routeClass:(Class)objectClass toResourcePathPattern:(NSString *)resourcePathPattern; /** * Register a mapping from an object class to a resource path for a specific HTTP method. * @see RKPathMatcher */ -- (void)routeClass:(Class)objectClass toResourcePathPattern:(NSString*)resourcePathPattern forMethod:(RKRequestMethod)method; +- (void)routeClass:(Class)objectClass toResourcePathPattern:(NSString *)resourcePathPattern forMethod:(RKRequestMethod)method; /** * Register a mapping from an object class to a resource path for a specific HTTP method, @@ -63,13 +63,13 @@ * @"%2Fthis%2Fis%2Fthe%2Fpath". * @see RKPathMatcher */ -- (void)routeClass:(Class)objectClass toResourcePathPattern:(NSString*)resourcePathPattern forMethod:(RKRequestMethod)method escapeRoutedPath:(BOOL)addEscapes; +- (void)routeClass:(Class)objectClass toResourcePathPattern:(NSString *)resourcePathPattern forMethod:(RKRequestMethod)method escapeRoutedPath:(BOOL)addEscapes; @end // Method signatures being phased out @interface RKObjectRouter (CompatibilityAliases) -- (void)routeClass:(Class)objectClass toResourcePath:(NSString*)resourcePath; -- (void)routeClass:(Class)objectClass toResourcePath:(NSString*)resourcePath forMethod:(RKRequestMethod)method; -- (void)routeClass:(Class)objectClass toResourcePath:(NSString*)resourcePath forMethod:(RKRequestMethod)method escapeRoutedPath:(BOOL)addEscapes; +- (void)routeClass:(Class)objectClass toResourcePath:(NSString *)resourcePath; +- (void)routeClass:(Class)objectClass toResourcePath:(NSString *)resourcePath forMethod:(RKRequestMethod)method; +- (void)routeClass:(Class)objectClass toResourcePath:(NSString *)resourcePath forMethod:(RKRequestMethod)method escapeRoutedPath:(BOOL)addEscapes; @end diff --git a/Code/ObjectMapping/RKObjectRouter.m b/Code/ObjectMapping/RKObjectRouter.m index 3a5dd486f1..e577d34622 100644 --- a/Code/ObjectMapping/RKObjectRouter.m +++ b/Code/ObjectMapping/RKObjectRouter.m @@ -24,7 +24,8 @@ @implementation RKObjectRouter -- (id)init { +- (id)init +{ if ((self = [super init])) { _routes = [[NSMutableDictionary alloc] init]; } @@ -32,12 +33,14 @@ - (id)init { return self; } -- (void)dealloc { +- (void)dealloc +{ [_routes release]; [super dealloc]; } -- (void)routeClass:(Class)theClass toResourcePathPattern:(NSString *)resourcePathPattern forMethodName:(NSString *)methodName escapeRoutedPath:(BOOL)addEscapes { +- (void)routeClass:(Class)theClass toResourcePathPattern:(NSString *)resourcePathPattern forMethodName:(NSString *)methodName escapeRoutedPath:(BOOL)addEscapes +{ NSString *className = NSStringFromClass(theClass); if (nil == [_routes objectForKey:theClass]) { NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; @@ -55,7 +58,8 @@ - (void)routeClass:(Class)theClass toResourcePathPattern:(NSString *)resourcePat [classRoutes setValue:routeEntry forKey:methodName]; } -- (NSString *)HTTPVerbForMethod:(RKRequestMethod)method { +- (NSString *)HTTPVerbForMethod:(RKRequestMethod)method +{ switch (method) { case RKRequestMethodGET: return @"GET"; @@ -77,22 +81,26 @@ - (NSString *)HTTPVerbForMethod:(RKRequestMethod)method { // Public -- (void)routeClass:(Class)theClass toResourcePathPattern:(NSString *)resourcePathPattern { +- (void)routeClass:(Class)theClass toResourcePathPattern:(NSString *)resourcePathPattern +{ [self routeClass:theClass toResourcePathPattern:resourcePathPattern forMethodName:@"ANY" escapeRoutedPath:YES]; } -- (void)routeClass:(Class)theClass toResourcePathPattern:(NSString *)resourcePath forMethod:(RKRequestMethod)method { +- (void)routeClass:(Class)theClass toResourcePathPattern:(NSString *)resourcePath forMethod:(RKRequestMethod)method +{ [self routeClass:theClass toResourcePath:resourcePath forMethod:method escapeRoutedPath:YES]; } -- (void)routeClass:(Class)theClass toResourcePathPattern:(NSString *)resourcePath forMethod:(RKRequestMethod)method escapeRoutedPath:(BOOL)addEscapes { +- (void)routeClass:(Class)theClass toResourcePathPattern:(NSString *)resourcePath forMethod:(RKRequestMethod)method escapeRoutedPath:(BOOL)addEscapes +{ NSString *methodName = [self HTTPVerbForMethod:method]; [self routeClass:theClass toResourcePathPattern:resourcePath forMethodName:methodName escapeRoutedPath:addEscapes]; } #pragma mark RKRouter -- (NSString *)resourcePathForObject:(NSObject *)object method:(RKRequestMethod)method { +- (NSString *)resourcePathForObject:(NSObject *)object method:(RKRequestMethod)method +{ NSString *methodName = [self HTTPVerbForMethod:method]; NSString *className = NSStringFromClass([object class]); NSDictionary *classRoutes = nil; @@ -136,15 +144,18 @@ - (NSString *)resourcePathForObject:(NSObject *)object method:(RKRequestMethod)m @implementation RKObjectRouter (CompatibilityAliases) -- (void)routeClass:(Class)objectClass toResourcePath:(NSString *)resourcePath { +- (void)routeClass:(Class)objectClass toResourcePath:(NSString *)resourcePath +{ [self routeClass:objectClass toResourcePathPattern:resourcePath]; } -- (void)routeClass:(Class)objectClass toResourcePath:(NSString *)resourcePath forMethod:(RKRequestMethod)method { +- (void)routeClass:(Class)objectClass toResourcePath:(NSString *)resourcePath forMethod:(RKRequestMethod)method +{ [self routeClass:objectClass toResourcePathPattern:resourcePath forMethod:method]; } -- (void)routeClass:(Class)objectClass toResourcePath:(NSString *)resourcePath forMethod:(RKRequestMethod)method escapeRoutedPath:(BOOL)addEscapes { +- (void)routeClass:(Class)objectClass toResourcePath:(NSString *)resourcePath forMethod:(RKRequestMethod)method escapeRoutedPath:(BOOL)addEscapes +{ [self routeClass:objectClass toResourcePathPattern:resourcePath forMethod:method escapeRoutedPath:addEscapes]; } diff --git a/Code/ObjectMapping/RKObjectSerializer.h b/Code/ObjectMapping/RKObjectSerializer.h index 87758e672c..c03fe7f7d2 100644 --- a/Code/ObjectMapping/RKObjectSerializer.h +++ b/Code/ObjectMapping/RKObjectSerializer.h @@ -28,36 +28,33 @@ transformed object is then enclosed in an RKRequestSerializable representation that is suitable for inclusion in an RKRequest. */ -@interface RKObjectSerializer : NSObject { - id _object; - RKObjectMapping* _mapping; -} +@interface RKObjectSerializer : NSObject @property (nonatomic, readonly) id object; -@property (nonatomic, readonly) RKObjectMapping* mapping; +@property (nonatomic, readonly) RKObjectMapping *mapping; -+ (id)serializerWithObject:(id)object mapping:(RKObjectMapping*)mapping; -- (id)initWithObject:(id)object mapping:(RKObjectMapping*)mapping; ++ (id)serializerWithObject:(id)object mapping:(RKObjectMapping *)mapping; +- (id)initWithObject:(id)object mapping:(RKObjectMapping *)mapping; /** Return a serialized representation of the source object by applying an object mapping with a target object type of NSMutableDictionary. The serialized object will contain attributes and relationships composed of simple KVC compliant Cocoa types. */ -- (NSMutableDictionary*)serializedObject:(NSError**)error; +- (NSMutableDictionary *)serializedObject:(NSError **)error; /** Return a serialized representation of the source object by mapping it into a NSMutableDictionary and then encoding it into the destination MIME Type via an instance of RKParser that is registered for the specified MIME Type */ -- (NSString*)serializedObjectForMIMEType:(NSString*)MIMEType error:(NSError**)error; +- (NSString *)serializedObjectForMIMEType:(NSString *)MIMEType error:(NSError **)error; /** Return a request serialization for the source object by mapping it to an NSMutableDictionary, encoding the data via a parser into the specified MIME Type, and wrapping it into a serializable format that can be used as the params of an RKRequest or RKObjectLoader */ -- (id)serializationForMIMEType:(NSString*)mimeType error:(NSError**)error; +- (id)serializationForMIMEType:(NSString *)mimeType error:(NSError **)error; @end diff --git a/Code/ObjectMapping/RKObjectSerializer.m b/Code/ObjectMapping/RKObjectSerializer.m index aecdcf890c..8991c1bd2c 100644 --- a/Code/ObjectMapping/RKObjectSerializer.m +++ b/Code/ObjectMapping/RKObjectSerializer.m @@ -35,11 +35,13 @@ @implementation RKObjectSerializer @synthesize object = _object; @synthesize mapping = _mapping; -+ (id)serializerWithObject:(id)object mapping:(RKObjectMapping*)mapping { ++ (id)serializerWithObject:(id)object mapping:(RKObjectMapping *)mapping +{ return [[[self alloc] initWithObject:object mapping:mapping] autorelease]; } -- (id)initWithObject:(id)object mapping:(RKObjectMapping*)mapping { +- (id)initWithObject:(id)object mapping:(RKObjectMapping *)mapping +{ self = [super init]; if (self) { _object = [object retain]; @@ -48,7 +50,8 @@ - (id)initWithObject:(id)object mapping:(RKObjectMapping*)mapping { return self; } -- (void)dealloc { +- (void)dealloc +{ [_object release]; [_mapping release]; @@ -56,9 +59,10 @@ - (void)dealloc { } // Return it serialized into a dictionary -- (id)serializedObject:(NSError**)error { - NSMutableDictionary* dictionary = [NSMutableDictionary dictionary]; - RKObjectMappingOperation* operation = [RKObjectMappingOperation mappingOperationFromObject:_object toObject:dictionary withMapping:_mapping]; +- (id)serializedObject:(NSError **)error +{ + NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; + RKObjectMappingOperation *operation = [RKObjectMappingOperation mappingOperationFromObject:_object toObject:dictionary withMapping:_mapping]; operation.delegate = self; BOOL success = [operation performMapping:error]; if (!success) { @@ -74,12 +78,13 @@ - (id)serializedObject:(NSError**)error { return dictionary; } -- (id)serializedObjectForMIMEType:(NSString*)MIMEType error:(NSError**)error { +- (id)serializedObjectForMIMEType:(NSString *)MIMEType error:(NSError **)error +{ // TODO: This will fail for form encoded... id serializedObject = [self serializedObject:error]; if (serializedObject) { id parser = [[RKParserRegistry sharedRegistry] parserForMIMEType:MIMEType]; - NSString* string = [parser stringFromObject:serializedObject error:error]; + NSString *string = [parser stringFromObject:serializedObject error:error]; if (string == nil) { return nil; } @@ -90,14 +95,15 @@ - (id)serializedObjectForMIMEType:(NSString*)MIMEType error:(NSError**)error { return nil; } -- (id)serializationForMIMEType:(NSString *)MIMEType error:(NSError **)error { +- (id)serializationForMIMEType:(NSString *)MIMEType error:(NSError **)error +{ if ([MIMEType isEqualToString:RKMIMETypeFormURLEncoded]) { // Dictionaries are natively RKRequestSerializable as Form Encoded return [self serializedObject:error]; } else { - NSString* string = [self serializedObjectForMIMEType:MIMEType error:error]; + NSString *string = [self serializedObjectForMIMEType:MIMEType error:error]; if (string) { - NSData* data = [string dataUsingEncoding:NSUTF8StringEncoding]; + NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding]; return [RKRequestSerialization serializationWithData:data MIMEType:MIMEType]; } } @@ -107,7 +113,8 @@ - (id)serializedObjectForMIMEType:(NSString*)MIMEType error:(NSError**)error { #pragma mark - RKObjectMappingOperationDelegate -- (void)objectMappingOperation:(RKObjectMappingOperation *)operation didSetValue:(id)value forKeyPath:(NSString *)keyPath usingMapping:(RKObjectAttributeMapping *)mapping { +- (void)objectMappingOperation:(RKObjectMappingOperation *)operation didSetValue:(id)value forKeyPath:(NSString *)keyPath usingMapping:(RKObjectAttributeMapping *)mapping +{ id transformedValue = nil; Class orderedSetClass = NSClassFromString(@"NSOrderedSet"); @@ -118,7 +125,7 @@ - (void)objectMappingOperation:(RKObjectMappingOperation *)operation didSetValue } } else if ([value isKindOfClass:[NSDecimalNumber class]]) { // Precision numbers are serialized as strings to work around Javascript notation limits - transformedValue = [(NSDecimalNumber*)value stringValue]; + transformedValue = [(NSDecimalNumber *)value stringValue]; } else if ([value isKindOfClass:orderedSetClass]) { // NSOrderedSets are not natively serializable, so let's just turn it into an NSArray transformedValue = [value array]; diff --git a/Code/ObjectMapping/RKParserRegistry.m b/Code/ObjectMapping/RKParserRegistry.m index 16ede88d42..11e929558a 100644 --- a/Code/ObjectMapping/RKParserRegistry.m +++ b/Code/ObjectMapping/RKParserRegistry.m @@ -24,7 +24,8 @@ @implementation RKParserRegistry -+ (RKParserRegistry *)sharedRegistry { ++ (RKParserRegistry *)sharedRegistry +{ if (gSharedRegistry == nil) { gSharedRegistry = [RKParserRegistry new]; [gSharedRegistry autoconfigure]; @@ -33,13 +34,15 @@ + (RKParserRegistry *)sharedRegistry { return gSharedRegistry; } -+ (void)setSharedRegistry:(RKParserRegistry *)registry { ++ (void)setSharedRegistry:(RKParserRegistry *)registry +{ [registry retain]; [gSharedRegistry release]; gSharedRegistry = registry; } -- (id)init { +- (id)init +{ self = [super init]; if (self) { _MIMETypeToParserClasses = [[NSMutableDictionary alloc] init]; @@ -49,13 +52,15 @@ - (id)init { return self; } -- (void)dealloc { +- (void)dealloc +{ [_MIMETypeToParserClasses release]; [_MIMETypeToParserClassesRegularExpressions release]; [super dealloc]; } -- (Class)parserClassForMIMEType:(NSString *)MIMEType { +- (Class)parserClassForMIMEType:(NSString *)MIMEType +{ id parserClass = [_MIMETypeToParserClasses objectForKey:MIMEType]; #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 1070 || __IPHONE_OS_VERSION_MAX_ALLOWED >= 40000 if (!parserClass) @@ -73,20 +78,23 @@ - (void)dealloc { return parserClass; } -- (void)setParserClass:(Class)parserClass forMIMEType:(NSString *)MIMEType { +- (void)setParserClass:(Class)parserClass forMIMEType:(NSString *)MIMEType +{ [_MIMETypeToParserClasses setObject:parserClass forKey:MIMEType]; } #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 1070 || __IPHONE_OS_VERSION_MAX_ALLOWED >= 40000 -- (void)setParserClass:(Class)parserClass forMIMETypeRegularExpression:(NSRegularExpression *)MIMETypeRegex { +- (void)setParserClass:(Class)parserClass forMIMETypeRegularExpression:(NSRegularExpression *)MIMETypeRegex +{ NSArray *expressionAndClass = [NSArray arrayWithObjects:MIMETypeRegex, parserClass, nil]; [_MIMETypeToParserClassesRegularExpressions addObject:expressionAndClass]; } #endif -- (id)parserForMIMEType:(NSString *)MIMEType { +- (id)parserForMIMEType:(NSString *)MIMEType +{ Class parserClass = [self parserClassForMIMEType:MIMEType]; if (parserClass) { return [[[parserClass alloc] init] autorelease]; @@ -95,7 +103,8 @@ - (void)setParserClass:(Class)parserClass forMIMETypeRegularExpression return nil; } -- (void)autoconfigure { +- (void)autoconfigure +{ Class parserClass = nil; // JSON diff --git a/Code/ObjectMapping/RKRouter.h b/Code/ObjectMapping/RKRouter.h index 6d6c06383c..d5d9b26ffa 100644 --- a/Code/ObjectMapping/RKRouter.h +++ b/Code/ObjectMapping/RKRouter.h @@ -29,6 +29,6 @@ /** * Returns the resource path to send requests for a given object and HTTP method */ -- (NSString*)resourcePathForObject:(NSObject*)object method:(RKRequestMethod)method; +- (NSString *)resourcePathForObject:(NSObject *)object method:(RKRequestMethod)method; @end diff --git a/Code/Support/NSArray+RKAdditions.m b/Code/Support/NSArray+RKAdditions.m index f632b1bbd6..4b12dd6d2a 100644 --- a/Code/Support/NSArray+RKAdditions.m +++ b/Code/Support/NSArray+RKAdditions.m @@ -16,7 +16,7 @@ - (NSArray *)sectionsGroupedByKeyPath:(NSString *)keyPath NSMutableArray *sections = [NSMutableArray array]; // If we don't contain any items, return an empty collection of sections. - if([self count] == 0) { + if ([self count] == 0) { return sections; } diff --git a/Code/Support/NSBundle+RKAdditions.m b/Code/Support/NSBundle+RKAdditions.m index eed3412e57..e3cec32586 100644 --- a/Code/Support/NSBundle+RKAdditions.m +++ b/Code/Support/NSBundle+RKAdditions.m @@ -27,7 +27,8 @@ @implementation NSBundle (RKAdditions) -+ (NSBundle *)restKitResourcesBundle { ++ (NSBundle *)restKitResourcesBundle +{ static BOOL searchedForBundle = NO; if (! searchedForBundle) { @@ -41,7 +42,8 @@ + (NSBundle *)restKitResourcesBundle { return [NSBundle bundleWithIdentifier:@"org.restkit.RestKitResources"]; } -- (NSString *)MIMETypeForResource:(NSString *)name withExtension:(NSString *)extension { +- (NSString *)MIMETypeForResource:(NSString *)name withExtension:(NSString *)extension +{ NSString *resourcePath = [self pathForResource:name ofType:extension]; if (resourcePath) { return [resourcePath MIMETypeForPathExtension]; @@ -50,7 +52,8 @@ - (NSString *)MIMETypeForResource:(NSString *)name withExtension:(NSString *)ext return nil; } -- (NSData *)dataWithContentsOfResource:(NSString *)name withExtension:(NSString *)extension { +- (NSData *)dataWithContentsOfResource:(NSString *)name withExtension:(NSString *)extension +{ NSString *resourcePath = [self pathForResource:name ofType:extension]; if (! resourcePath) { RKLogWarning(@"%@ Failed to locate Resource with name '%@' and extension '%@': File Not Found.", self, resourcePath, extension); @@ -60,15 +63,16 @@ - (NSData *)dataWithContentsOfResource:(NSString *)name withExtension:(NSString return [NSData dataWithContentsOfFile:resourcePath]; } -- (NSString *)stringWithContentsOfResource:(NSString *)name withExtension:(NSString *)extension encoding:(NSStringEncoding)encoding { - NSError* error = nil; +- (NSString *)stringWithContentsOfResource:(NSString *)name withExtension:(NSString *)extension encoding:(NSStringEncoding)encoding +{ + NSError *error = nil; NSString *resourcePath = [self pathForResource:name ofType:extension]; if (! resourcePath) { RKLogWarning(@"%@ Failed to locate Resource with name '%@' and extension '%@': File Not Found.", self, resourcePath, extension); return nil; } - NSString* fixtureData = [NSString stringWithContentsOfFile:resourcePath encoding:encoding error:&error]; + NSString *fixtureData = [NSString stringWithContentsOfFile:resourcePath encoding:encoding error:&error]; if (fixtureData == nil && error) { RKLogWarning(@"Failed to read "); } @@ -77,7 +81,8 @@ - (NSString *)stringWithContentsOfResource:(NSString *)name withExtension:(NSStr } #if TARGET_OS_IPHONE -- (UIImage *)imageWithContentsOfResource:(NSString *)name withExtension:(NSString *)extension { +- (UIImage *)imageWithContentsOfResource:(NSString *)name withExtension:(NSString *)extension +{ NSString *resourcePath = [self pathForResource:name ofType:extension]; if (! resourcePath) { RKLogWarning(@"%@ Failed to locate Resource with name '%@' and extension '%@': File Not Found.", self, resourcePath, extension); @@ -88,10 +93,11 @@ - (UIImage *)imageWithContentsOfResource:(NSString *)name withExtension:(NSStrin } #endif -- (id)parsedObjectWithContentsOfResource:(NSString *)name withExtension:(NSString *)extension { - NSError* error = nil; - NSString* resourceContents = [self stringWithContentsOfResource:name withExtension:extension encoding:NSUTF8StringEncoding]; - NSString* MIMEType = [self MIMETypeForResource:name withExtension:extension]; +- (id)parsedObjectWithContentsOfResource:(NSString *)name withExtension:(NSString *)extension +{ + NSError *error = nil; + NSString *resourceContents = [self stringWithContentsOfResource:name withExtension:extension encoding:NSUTF8StringEncoding]; + NSString *MIMEType = [self MIMETypeForResource:name withExtension:extension]; id parser = [[RKParserRegistry sharedRegistry] parserForMIMEType:MIMEType]; if (! parser) { RKLogError(@"%@ Unable to parse Resource with name '%@' and extension '%@': failed to find parser registered to handle MIME Type '%@'", self, name, extension, MIMEType); diff --git a/Code/Support/NSDictionary+RKAdditions.m b/Code/Support/NSDictionary+RKAdditions.m index dc5d79454a..84daab2d1f 100644 --- a/Code/Support/NSDictionary+RKAdditions.m +++ b/Code/Support/NSDictionary+RKAdditions.m @@ -26,11 +26,12 @@ @implementation NSDictionary (RKAdditions) -+ (id)dictionaryWithKeysAndObjects:(id)firstKey, ... { ++ (id)dictionaryWithKeysAndObjects:(id)firstKey, ... +{ va_list args; va_start(args, firstKey); - NSMutableArray* keys = [NSMutableArray array]; - NSMutableArray* values = [NSMutableArray array]; + NSMutableArray *keys = [NSMutableArray array]; + NSMutableArray *values = [NSMutableArray array]; for (id key = firstKey; key != nil; key = va_arg(args, id)) { id value = va_arg(args, id); [keys addObject:key]; @@ -41,7 +42,8 @@ + (id)dictionaryWithKeysAndObjects:(id)firstKey, ... { return [self dictionaryWithObjects:values forKeys:keys]; } -- (NSDictionary *)dictionaryByReplacingPercentEscapesInEntries { +- (NSDictionary *)dictionaryByReplacingPercentEscapesInEntries +{ NSMutableDictionary *results = [NSMutableDictionary dictionaryWithCapacity:[self count]]; [self enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) { @@ -55,9 +57,10 @@ - (NSDictionary *)dictionaryByReplacingPercentEscapesInEntries { } // TODO: Unit tests... -+ (NSDictionary *)dictionaryWithURLEncodedString:(NSString *)URLEncodedString { ++ (NSDictionary *)dictionaryWithURLEncodedString:(NSString *)URLEncodedString +{ NSMutableDictionary *queryComponents = [NSMutableDictionary dictionary]; - for(NSString *keyValuePairString in [URLEncodedString componentsSeparatedByString:@"&"]) { + for (NSString *keyValuePairString in [URLEncodedString componentsSeparatedByString:@"&"]) { NSArray *keyValuePairArray = [keyValuePairString componentsSeparatedByString:@"="]; if ([keyValuePairArray count] < 2) continue; // Verify that there is at least one key, and at least one value. Ignore extra = signs NSString *key = [[keyValuePairArray objectAtIndex:0] stringByReplacingURLEncoding]; @@ -65,7 +68,7 @@ + (NSDictionary *)dictionaryWithURLEncodedString:(NSString *)URLEncodedString { // URL spec says that multiple values are allowed per key id results = [queryComponents objectForKey:key]; - if(results) { + if (results) { if ([results isKindOfClass:[NSMutableArray class]]) { [(NSMutableArray *)results addObject:value]; } else { @@ -81,12 +84,14 @@ + (NSDictionary *)dictionaryWithURLEncodedString:(NSString *)URLEncodedString { return queryComponents; } -- (void)URLEncodePart:(NSMutableArray*)parts path:(NSString*)path value:(id)value { +- (void)URLEncodePart:(NSMutableArray *)parts path:(NSString *)path value:(id)value +{ NSString *encodedPart = [[value description] stringByAddingURLEncoding]; - [parts addObject:[NSString stringWithFormat: @"%@=%@", path, encodedPart]]; + [parts addObject:[NSString stringWithFormat:@"%@=%@", path, encodedPart]]; } -- (void)URLEncodeParts:(NSMutableArray*)parts path:(NSString*)inPath { +- (void)URLEncodeParts:(NSMutableArray *)parts path:(NSString *)inPath +{ [self enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) { NSString *encodedKey = [[key description] stringByAddingURLEncoding]; NSString *path = inPath ? [inPath stringByAppendingFormat:@"[%@]", encodedKey] : encodedKey; @@ -100,7 +105,7 @@ - (void)URLEncodeParts:(NSMutableArray*)parts path:(NSString*)inPath { } } - } else if([value isKindOfClass:[NSDictionary class]] || [value isKindOfClass:[NSMutableDictionary class]]) { + } else if ([value isKindOfClass:[NSDictionary class]] || [value isKindOfClass:[NSMutableDictionary class]]) { [value URLEncodeParts:parts path:path]; } else { @@ -109,13 +114,15 @@ - (void)URLEncodeParts:(NSMutableArray*)parts path:(NSString*)inPath { }]; } -- (NSString *)stringWithURLEncodedEntries { - NSMutableArray* parts = [NSMutableArray array]; +- (NSString *)stringWithURLEncodedEntries +{ + NSMutableArray *parts = [NSMutableArray array]; [self URLEncodeParts:parts path:nil]; return [parts componentsJoinedByString:@"&"]; } -- (NSString *)URLEncodedString { +- (NSString *)URLEncodedString +{ return [self stringWithURLEncodedEntries]; } diff --git a/Code/Support/NSString+RKAdditions.h b/Code/Support/NSString+RKAdditions.h index b5a21bbc7b..520865c515 100644 --- a/Code/Support/NSString+RKAdditions.h +++ b/Code/Support/NSString+RKAdditions.h @@ -32,12 +32,12 @@ when given a resourcePath of /contacts and a dictionary of parameters containing foo=bar and color=red, will return /contacts?foo=bar&color=red - *NOTE* - Assumes that the resource path does not already contain any query parameters. + *NOTE *- Assumes that the resource path does not already contain any query parameters. @param queryParameters A dictionary of query parameters to be URL encoded and appended to the resource path @return A new resource path with the query parameters appended */ - (NSString *)stringByAppendingQueryParameters:(NSDictionary *)queryParameters; -- (NSString *)appendQueryParams:(NSDictionary*)queryParams DEPRECATED_ATTRIBUTE; +- (NSString *)appendQueryParams:(NSDictionary *)queryParams DEPRECATED_ATTRIBUTE; /** Convenience method for generating a path against the properties of an object. Takes diff --git a/Code/Support/NSString+RKAdditions.m b/Code/Support/NSString+RKAdditions.m index b53e85d89c..3b1fcada0b 100644 --- a/Code/Support/NSString+RKAdditions.m +++ b/Code/Support/NSString+RKAdditions.m @@ -37,7 +37,8 @@ @implementation NSString (RKAdditions) -- (NSString *)stringByAppendingQueryParameters:(NSDictionary *)queryParameters { +- (NSString *)stringByAppendingQueryParameters:(NSDictionary *)queryParameters +{ if ([queryParameters count] > 0) { return [NSString stringWithFormat:@"%@?%@", self, [queryParameters stringWithURLEncodedEntries]]; } @@ -45,61 +46,67 @@ - (NSString *)stringByAppendingQueryParameters:(NSDictionary *)queryParameters { } // Deprecated -- (NSString *)appendQueryParams:(NSDictionary *)queryParams { +- (NSString *)appendQueryParams:(NSDictionary *)queryParams +{ return [self stringByAppendingQueryParameters:queryParams]; } -- (NSString *)interpolateWithObject:(id)object addingEscapes:(BOOL)addEscapes { +- (NSString *)interpolateWithObject:(id)object addingEscapes:(BOOL)addEscapes +{ NSCAssert(object != NULL, @"Object provided is invalid; cannot create a path from a NULL object"); RKPathMatcher *matcher = [RKPathMatcher matcherWithPattern:self]; NSString *interpolatedPath = [matcher pathFromObject:object addingEscapes:addEscapes]; return interpolatedPath; } -- (NSString *)interpolateWithObject:(id)object { +- (NSString *)interpolateWithObject:(id)object +{ return [self interpolateWithObject:object addingEscapes:YES]; } -- (NSDictionary *)queryParameters { +- (NSDictionary *)queryParameters +{ return [self queryParametersUsingEncoding:NSUTF8StringEncoding]; } -- (NSDictionary*)queryParametersUsingEncoding:(NSStringEncoding)encoding { +- (NSDictionary *)queryParametersUsingEncoding:(NSStringEncoding)encoding +{ return [self queryParametersUsingArrays:NO encoding:encoding]; } // TODO: Eliminate... -- (NSDictionary*)queryParametersUsingArrays:(BOOL)shouldUseArrays encoding:(NSStringEncoding)encoding { +- (NSDictionary *)queryParametersUsingArrays:(BOOL)shouldUseArrays encoding:(NSStringEncoding)encoding +{ NSString *stringToParse = self; NSRange chopRange = [stringToParse rangeOfString:@"?"]; if (chopRange.length > 0) { - chopRange.location+=1; // we want inclusive chopping up *through* "?" + chopRange.location += 1; // we want inclusive chopping up *through *"?" if (chopRange.location < [stringToParse length]) stringToParse = [stringToParse substringFromIndex:chopRange.location]; } - NSCharacterSet* delimiterSet = [NSCharacterSet characterSetWithCharactersInString:@"&;"]; - NSMutableDictionary* pairs = [NSMutableDictionary dictionary]; - NSScanner* scanner = [[[NSScanner alloc] initWithString:stringToParse] autorelease]; + NSCharacterSet *delimiterSet = [NSCharacterSet characterSetWithCharactersInString:@"&;"]; + NSMutableDictionary *pairs = [NSMutableDictionary dictionary]; + NSScanner *scanner = [[[NSScanner alloc] initWithString:stringToParse] autorelease]; while (![scanner isAtEnd]) { - NSString* pairString = nil; + NSString *pairString = nil; [scanner scanUpToCharactersFromSet:delimiterSet intoString:&pairString]; [scanner scanCharactersFromSet:delimiterSet intoString:NULL]; - NSArray* kvPair = [pairString componentsSeparatedByString:@"="]; + NSArray *kvPair = [pairString componentsSeparatedByString:@"="]; if (!shouldUseArrays) { if (kvPair.count == 2) { - NSString* key = [[kvPair objectAtIndex:0] + NSString *key = [[kvPair objectAtIndex:0] stringByReplacingPercentEscapesUsingEncoding:encoding]; - NSString* value = [[kvPair objectAtIndex:1] + NSString *value = [[kvPair objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:encoding]; [pairs setObject:value forKey:key]; } } else { if (kvPair.count == 1 || kvPair.count == 2) { - NSString* key = [[kvPair objectAtIndex:0] + NSString *key = [[kvPair objectAtIndex:0] stringByReplacingPercentEscapesUsingEncoding:encoding]; - NSMutableArray* values = [pairs objectForKey:key]; + NSMutableArray *values = [pairs objectForKey:key]; if (nil == values) { values = [NSMutableArray array]; [pairs setObject:values forKey:key]; @@ -108,7 +115,7 @@ - (NSDictionary*)queryParametersUsingArrays:(BOOL)shouldUseArrays encoding:(NSSt [values addObject:[NSNull null]]; } else if (kvPair.count == 2) { - NSString* value = [[kvPair objectAtIndex:1] + NSString *value = [[kvPair objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:encoding]; [values addObject:value]; } @@ -119,7 +126,8 @@ - (NSDictionary*)queryParametersUsingArrays:(BOOL)shouldUseArrays encoding:(NSSt } // NOTE: See http://en.wikipedia.org/wiki/Percent-encoding#Percent-encoding_reserved_characters -- (NSString *)stringByAddingURLEncoding { +- (NSString *)stringByAddingURLEncoding +{ CFStringRef legalURLCharactersToBeEscaped = CFSTR(":/?#[]@!$ &'()*+,;=\"<>%{}|\\^~`\n\r"); CFStringRef encodedString = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)self, @@ -134,17 +142,20 @@ - (NSString *)stringByAddingURLEncoding { return @""; } -- (NSString *)stringByReplacingURLEncoding { +- (NSString *)stringByReplacingURLEncoding +{ return [self stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; } -- (NSDictionary *)fileExtensionsToMIMETypesDictionary { +- (NSDictionary *)fileExtensionsToMIMETypesDictionary +{ return [NSDictionary dictionaryWithObjectsAndKeys:@"application/json", @"json", nil]; } -- (NSString *)MIMETypeForPathExtension { +- (NSString *)MIMETypeForPathExtension +{ NSString *fileExtension = [self pathExtension]; - CFStringRef uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (CFStringRef) fileExtension, NULL); + CFStringRef uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (CFStringRef)fileExtension, NULL); if (uti != NULL) { CFStringRef mime = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType); CFRelease(uti); @@ -159,33 +170,36 @@ - (NSString *)MIMETypeForPathExtension { return [[self fileExtensionsToMIMETypesDictionary] valueForKey:fileExtension]; } -- (BOOL)isIPAddress { +- (BOOL)isIPAddress +{ struct sockaddr_in sa; - char *hostNameOrIPAddressCString = (char *) [self UTF8String]; + char *hostNameOrIPAddressCString = (char *)[self UTF8String]; int result = inet_pton(AF_INET, hostNameOrIPAddressCString, &(sa.sin_addr)); return (result != 0); } -- (NSString *)stringByAppendingPathComponent:(NSString *)pathComponent isDirectory:(BOOL)isDirectory { +- (NSString *)stringByAppendingPathComponent:(NSString *)pathComponent isDirectory:(BOOL)isDirectory +{ NSString *stringWithPathComponent = [self stringByAppendingPathComponent:pathComponent]; if (isDirectory) return [stringWithPathComponent stringByAppendingString:@"/"]; return stringWithPathComponent; } -- (NSString *)MD5 { +- (NSString *)MD5 +{ // Create pointer to the string as UTF8 - const char* ptr = [self UTF8String]; + const char *ptr = [self UTF8String]; // Create byte array of unsigned chars unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH]; // Create 16 byte MD5 hash value, store in buffer - CC_MD5(ptr, (CC_LONG) strlen(ptr), md5Buffer); + CC_MD5(ptr, (CC_LONG)strlen(ptr), md5Buffer); // Convert MD5 value in the buffer to NSString of hex values - NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2]; + NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH *2]; for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) { - [output appendFormat:@"%02x",md5Buffer[i]]; + [output appendFormat:@"%02x", md5Buffer[i]]; } return output; diff --git a/Code/Support/NSURL+RKAdditions.m b/Code/Support/NSURL+RKAdditions.m index ee937f8375..8f2d8dc202 100644 --- a/Code/Support/NSURL+RKAdditions.m +++ b/Code/Support/NSURL+RKAdditions.m @@ -27,11 +27,13 @@ @implementation NSURL (RKAdditions) -- (NSDictionary *)queryParameters { +- (NSDictionary *)queryParameters +{ return [NSDictionary dictionaryWithURLEncodedString:self.query]; } -- (NSString *)MIMETypeForPathExtension { +- (NSString *)MIMETypeForPathExtension +{ return [[self path] MIMETypeForPathExtension]; } diff --git a/Code/Support/Parsers/JSON/RKJSONParserJSONKit.m b/Code/Support/Parsers/JSON/RKJSONParserJSONKit.m index 56f6ebf756..d3bf2338d9 100644 --- a/Code/Support/Parsers/JSON/RKJSONParserJSONKit.m +++ b/Code/Support/Parsers/JSON/RKJSONParserJSONKit.m @@ -31,12 +31,14 @@ // the internal caching capabilities from the JSONKit serializer @implementation RKJSONParserJSONKit -- (NSDictionary*)objectFromString:(NSString*)string error:(NSError**)error { +- (NSDictionary *)objectFromString:(NSString *)string error:(NSError **)error +{ RKLogTrace(@"string='%@'", string); return [string objectFromJSONStringWithParseOptions:JKParseOptionStrict error:error]; } -- (NSString*)stringFromObject:(id)object error:(NSError**)error { +- (NSString *)stringFromObject:(id)object error:(NSError **)error +{ return [object JSONStringWithOptions:JKSerializeOptionNone error:error]; } diff --git a/Code/Support/Parsers/XML/RKXMLParserXMLReader.m b/Code/Support/Parsers/XML/RKXMLParserXMLReader.m index ed9a7dfc80..e6bd8fdaf8 100644 --- a/Code/Support/Parsers/XML/RKXMLParserXMLReader.m +++ b/Code/Support/Parsers/XML/RKXMLParserXMLReader.m @@ -10,12 +10,14 @@ @implementation RKXMLParserXMLReader -- (id)objectFromString:(NSString*)string error:(NSError**)error { +- (id)objectFromString:(NSString *)string error:(NSError **)error +{ NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding]; return [XMLReader dictionaryForXMLData:data error:error]; } -- (NSString*)stringFromObject:(id)object error:(NSError**)error { +- (NSString *)stringFromObject:(id)object error:(NSError **)error +{ return nil; } diff --git a/Code/Support/RKAlert.h b/Code/Support/RKAlert.h index 00e7ab49e8..65733fe7cc 100644 --- a/Code/Support/RKAlert.h +++ b/Code/Support/RKAlert.h @@ -23,9 +23,9 @@ /** * Presents an alert dialog with the specified message */ -void RKAlert(NSString* message); +void RKAlert(NSString *message); /** * Presents an alert dialog with the specified message and title */ -void RKAlertWithTitle(NSString* message, NSString* title); +void RKAlertWithTitle(NSString *message, NSString *title); diff --git a/Code/Support/RKAlert.m b/Code/Support/RKAlert.m index c6ed0f64eb..8df44735b2 100644 --- a/Code/Support/RKAlert.m +++ b/Code/Support/RKAlert.m @@ -27,13 +27,13 @@ #import "RKAlert.h" #import "RKLog.h" -void RKAlert(NSString* message) { +void RKAlert(NSString *message) { RKAlertWithTitle(message, @"Alert"); } -void RKAlertWithTitle(NSString* message, NSString* title) { +void RKAlertWithTitle(NSString *message, NSString *title) { #if TARGET_OS_IPHONE - UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:title + UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title message:message delegate:nil cancelButtonTitle:NSLocalizedString(@"OK", nil) diff --git a/Code/Support/RKBenchmark.m b/Code/Support/RKBenchmark.m index 99124cb767..53c0e5e886 100644 --- a/Code/Support/RKBenchmark.m +++ b/Code/Support/RKBenchmark.m @@ -18,16 +18,18 @@ @interface RKBenchmark () @implementation RKBenchmark -static NSMutableDictionary * __sharedBenchmarks = nil; +static NSMutableDictionary *__sharedBenchmarks = nil; -+ (NSMutableDictionary *)sharedBenchmarks { ++ (NSMutableDictionary *)sharedBenchmarks +{ if (!__sharedBenchmarks) { __sharedBenchmarks = [[NSMutableDictionary alloc] init]; } return __sharedBenchmarks; } -+ (id)instanceWithName:(NSString *)name { ++ (id)instanceWithName:(NSString *)name +{ @synchronized (self) { // get the benchmark or create it on-the-fly id benchmark = [[self sharedBenchmarks] objectForKey:name]; @@ -49,14 +51,16 @@ + (id)instanceWithName:(NSString *)name { # pragma mark - # pragma mark Quick access class methods -+ (id)report:(NSString *)info executionBlock:(void (^)(void))block { ++ (id)report:(NSString *)info executionBlock:(void (^)(void))block +{ RKBenchmark *benchmark = [self instanceWithName:info]; [benchmark run:block]; [benchmark log]; return benchmark; } -+ (CFTimeInterval)measureWithExecutionBlock:(void (^)(void))block { ++ (CFTimeInterval)measureWithExecutionBlock:(void (^)(void))block +{ RKBenchmark *benchmark = [[self new] autorelease]; [benchmark run:block]; return benchmark.elapsedTime; @@ -65,11 +69,13 @@ + (CFTimeInterval)measureWithExecutionBlock:(void (^)(void))block { # pragma mark - # pragma mark Initializers -+ (id)benchmarkWithName:(NSString *)name { ++ (id)benchmarkWithName:(NSString *)name +{ return [[[self alloc] initWithName:name] autorelease]; } -- (id)initWithName:(NSString *)name { +- (id)initWithName:(NSString *)name +{ if (self = [self init]) { self.name = name; } @@ -79,17 +85,20 @@ - (id)initWithName:(NSString *)name { # pragma mark - # pragma mark Benchmark methods -- (void)run:(void (^)(void))executionBlock { +- (void)run:(void (^)(void))executionBlock +{ [self start]; executionBlock(); [self stop]; } -- (void)start { +- (void)start +{ self.startTime = CFAbsoluteTimeGetCurrent(); } -- (void)stop { +- (void)stop +{ self.endTime = CFAbsoluteTimeGetCurrent(); self.stopped = YES; @@ -101,7 +110,8 @@ - (void)stop { CFRelease(endDate); } -- (void)log { +- (void)log +{ CFTimeInterval timeElapsed; if (self.isStopped) { timeElapsed = self.elapsedTime; diff --git a/Code/Support/RKCache.h b/Code/Support/RKCache.h index 1b5d590fe2..c872d82af8 100644 --- a/Code/Support/RKCache.h +++ b/Code/Support/RKCache.h @@ -19,20 +19,20 @@ // @interface RKCache : NSObject { - NSString* _cachePath; - NSRecursiveLock* _cacheLock; + NSString *_cachePath; + NSRecursiveLock *_cacheLock; } -@property (nonatomic, readonly) NSString* cachePath; +@property (nonatomic, readonly) NSString *cachePath; -- (id)initWithPath:(NSString*)cachePath subDirectories:(NSArray*)subDirectories; -- (BOOL)hasEntry:(NSString*)cacheKey; -- (void)invalidateEntry:(NSString*)cacheKey; -- (void)invalidateSubDirectory:(NSString*)subDirectory; +- (id)initWithPath:(NSString *)cachePath subDirectories:(NSArray *)subDirectories; +- (BOOL)hasEntry:(NSString *)cacheKey; +- (void)invalidateEntry:(NSString *)cacheKey; +- (void)invalidateSubDirectory:(NSString *)subDirectory; - (void)invalidateAll; -- (void)writeDictionary:(NSDictionary*)dictionary withCacheKey:(NSString*)cacheKey; -- (void)writeData:(NSData*)data withCacheKey:(NSString*)cacheKey; -- (NSDictionary*)dictionaryForCacheKey:(NSString*)cacheKey ; -- (NSData*)dataForCacheKey:(NSString*)cacheKey; +- (void)writeDictionary:(NSDictionary *)dictionary withCacheKey:(NSString *)cacheKey; +- (void)writeData:(NSData *)data withCacheKey:(NSString *)cacheKey; +- (NSDictionary *)dictionaryForCacheKey:(NSString *)cacheKey ; +- (NSData *)dataForCacheKey:(NSString *)cacheKey; @end diff --git a/Code/Support/RKCache.m b/Code/Support/RKCache.m index cc10686e17..27f07a1817 100644 --- a/Code/Support/RKCache.m +++ b/Code/Support/RKCache.m @@ -27,23 +27,24 @@ @implementation RKCache -- (id)initWithPath:(NSString*)cachePath subDirectories:(NSArray*)subDirectories { +- (id)initWithPath:(NSString *)cachePath subDirectories:(NSArray *)subDirectories +{ self = [super init]; if (self) { _cachePath = [cachePath copy]; _cacheLock = [[NSRecursiveLock alloc] init]; - NSFileManager* fileManager = [NSFileManager defaultManager]; - NSMutableArray* pathArray = [NSMutableArray arrayWithObject:_cachePath]; - for (NSString* subDirectory in subDirectories) { + NSFileManager *fileManager = [NSFileManager defaultManager]; + NSMutableArray *pathArray = [NSMutableArray arrayWithObject:_cachePath]; + for (NSString *subDirectory in subDirectories) { [pathArray addObject:[_cachePath stringByAppendingPathComponent:subDirectory]]; } - for (NSString* path in pathArray) { + for (NSString *path in pathArray) { BOOL isDirectory = NO; BOOL fileExists = [fileManager fileExistsAtPath:path isDirectory:&isDirectory]; if (!fileExists) { - NSError* error = nil; + NSError *error = nil; BOOL created = [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil @@ -63,7 +64,8 @@ - (id)initWithPath:(NSString*)cachePath subDirectories:(NSArray*)subDirectories return self; } -- (void)dealloc { +- (void)dealloc +{ [_cachePath release]; _cachePath = nil; [_cacheLock release]; @@ -71,30 +73,34 @@ - (void)dealloc { [super dealloc]; } -- (NSString*)cachePath { +- (NSString *)cachePath +{ return _cachePath; } -- (NSString*)pathForCacheKey:(NSString*)cacheKey { +- (NSString *)pathForCacheKey:(NSString *)cacheKey +{ [_cacheLock lock]; - NSString* pathForCacheKey = [_cachePath stringByAppendingPathComponent:cacheKey]; + NSString *pathForCacheKey = [_cachePath stringByAppendingPathComponent:cacheKey]; [_cacheLock unlock]; RKLogTrace(@"Found cachePath '%@' for %@", pathForCacheKey, cacheKey); return pathForCacheKey; } -- (BOOL)hasEntry:(NSString*)cacheKey { +- (BOOL)hasEntry:(NSString *)cacheKey +{ [_cacheLock lock]; BOOL hasEntry = NO; - NSFileManager* fileManager = [NSFileManager defaultManager]; - NSString* cachePath = [self pathForCacheKey:cacheKey]; + NSFileManager *fileManager = [NSFileManager defaultManager]; + NSString *cachePath = [self pathForCacheKey:cacheKey]; hasEntry = [fileManager fileExistsAtPath:cachePath]; [_cacheLock unlock]; RKLogTrace(@"Determined hasEntry: %@ => %@", cacheKey, hasEntry ? @"YES" : @"NO"); return hasEntry; } -- (void)writeDictionary:(NSDictionary*)dictionary withCacheKey:(NSString*)cacheKey { +- (void)writeDictionary:(NSDictionary *)dictionary withCacheKey:(NSString *)cacheKey +{ if (dictionary) { [_cacheLock lock]; RKLogTrace(@"Writing dictionary to cache key: '%@'", cacheKey); @@ -108,12 +114,13 @@ - (void)writeDictionary:(NSDictionary*)dictionary withCacheKey:(NSString*)cacheK } } -- (void)writeData:(NSData*)data withCacheKey:(NSString*)cacheKey { +- (void)writeData:(NSData *)data withCacheKey:(NSString *)cacheKey +{ if (data) { [_cacheLock lock]; - NSString* cachePath = [self pathForCacheKey:cacheKey]; + NSString *cachePath = [self pathForCacheKey:cacheKey]; if (cachePath) { - NSError* error = nil; + NSError *error = nil; BOOL success = [data writeToFile:cachePath options:NSDataWritingAtomic error:&error]; if (success) { RKLogTrace(@"Wrote cached data to path '%@'", cachePath); @@ -125,10 +132,11 @@ - (void)writeData:(NSData*)data withCacheKey:(NSString*)cacheKey { } } -- (NSDictionary*)dictionaryForCacheKey:(NSString*)cacheKey { +- (NSDictionary *)dictionaryForCacheKey:(NSString *)cacheKey +{ [_cacheLock lock]; - NSDictionary* dictionary = nil; - NSString* cachePath = [self pathForCacheKey:cacheKey]; + NSDictionary *dictionary = nil; + NSString *cachePath = [self pathForCacheKey:cacheKey]; if (cachePath) { dictionary = [NSDictionary dictionaryWithContentsOfFile:cachePath]; if (dictionary) { @@ -143,10 +151,11 @@ - (NSDictionary*)dictionaryForCacheKey:(NSString*)cacheKey { return dictionary; } -- (NSData*)dataForCacheKey:(NSString*)cacheKey { +- (NSData *)dataForCacheKey:(NSString *)cacheKey +{ [_cacheLock lock]; - NSData* data = nil; - NSString* cachePath = [self pathForCacheKey:cacheKey]; + NSData *data = nil; + NSString *cachePath = [self pathForCacheKey:cacheKey]; if (cachePath) { data = [NSData dataWithContentsOfFile:cachePath]; if (data) { @@ -159,35 +168,37 @@ - (NSData*)dataForCacheKey:(NSString*)cacheKey { return data; } -- (void)invalidateEntry:(NSString*)cacheKey { +- (void)invalidateEntry:(NSString *)cacheKey +{ [_cacheLock lock]; RKLogDebug(@"Invalidating cache entry for '%@'", cacheKey); - NSString* cachePath = [self pathForCacheKey:cacheKey]; + NSString *cachePath = [self pathForCacheKey:cacheKey]; if (cachePath) { - NSFileManager* fileManager = [NSFileManager defaultManager]; + NSFileManager *fileManager = [NSFileManager defaultManager]; [fileManager removeItemAtPath:cachePath error:NULL]; RKLogTrace(@"Removed cache entry at path '%@' for '%@'", cachePath, cacheKey); } [_cacheLock unlock]; } -- (void)invalidateSubDirectory:(NSString*)subDirectory { +- (void)invalidateSubDirectory:(NSString *)subDirectory +{ [_cacheLock lock]; if (_cachePath && subDirectory) { - NSString* subDirectoryPath = [_cachePath stringByAppendingPathComponent:subDirectory]; + NSString *subDirectoryPath = [_cachePath stringByAppendingPathComponent:subDirectory]; RKLogInfo(@"Invalidating cache at path: %@", subDirectoryPath); - NSFileManager* fileManager = [NSFileManager defaultManager]; + NSFileManager *fileManager = [NSFileManager defaultManager]; BOOL isDirectory = NO; BOOL fileExists = [fileManager fileExistsAtPath:subDirectoryPath isDirectory:&isDirectory]; if (fileExists && isDirectory) { - NSError* error = nil; - NSArray* cacheEntries = [fileManager contentsOfDirectoryAtPath:subDirectoryPath error:&error]; + NSError *error = nil; + NSArray *cacheEntries = [fileManager contentsOfDirectoryAtPath:subDirectoryPath error:&error]; if (nil == error) { - for (NSString* cacheEntry in cacheEntries) { - NSString* cacheEntryPath = [subDirectoryPath stringByAppendingPathComponent:cacheEntry]; + for (NSString *cacheEntry in cacheEntries) { + NSString *cacheEntryPath = [subDirectoryPath stringByAppendingPathComponent:cacheEntry]; [fileManager removeItemAtPath:cacheEntryPath error:&error]; if (nil != error) { RKLogError(@"Failed to delete cache entry for file: %@", cacheEntryPath); @@ -201,22 +212,23 @@ - (void)invalidateSubDirectory:(NSString*)subDirectory { [_cacheLock unlock]; } -- (void)invalidateAll { +- (void)invalidateAll +{ [_cacheLock lock]; if (_cachePath) { RKLogInfo(@"Invalidating cache at path: %@", _cachePath); - NSFileManager* fileManager = [NSFileManager defaultManager]; + NSFileManager *fileManager = [NSFileManager defaultManager]; BOOL isDirectory = NO; BOOL fileExists = [fileManager fileExistsAtPath:_cachePath isDirectory:&isDirectory]; if (fileExists && isDirectory) { - NSError* error = nil; - NSArray* cacheEntries = [fileManager contentsOfDirectoryAtPath:_cachePath error:&error]; + NSError *error = nil; + NSArray *cacheEntries = [fileManager contentsOfDirectoryAtPath:_cachePath error:&error]; if (nil == error) { - for (NSString* cacheEntry in cacheEntries) { - NSString* cacheEntryPath = [_cachePath stringByAppendingPathComponent:cacheEntry]; + for (NSString *cacheEntry in cacheEntries) { + NSString *cacheEntryPath = [_cachePath stringByAppendingPathComponent:cacheEntry]; [fileManager removeItemAtPath:cacheEntryPath error:&error]; if (nil != error) { RKLogError(@"Failed to delete cache entry for file: %@", cacheEntryPath); diff --git a/Code/Support/RKDotNetDateFormatter.h b/Code/Support/RKDotNetDateFormatter.h index 3e8466e7fb..56a98ef1bd 100644 --- a/Code/Support/RKDotNetDateFormatter.h +++ b/Code/Support/RKDotNetDateFormatter.h @@ -26,7 +26,7 @@ /** A subclass of NSDateFormatter that serves as translator between ASP.NET date serializations in JSON strings and NSDate objects. This is useful for properly mapping these dates from an ASP.NET driven backend. - *NOTE* - DO NOT attempt to use setDateFormat: on this class. It will return invalid results. + *NOTE *- DO NOT attempt to use setDateFormat: on this class. It will return invalid results. */ @interface RKDotNetDateFormatter : NSDateFormatter { NSRegularExpression *dotNetExpression; @@ -61,7 +61,7 @@ Where 1112715000000 is the number of milliseconds since January 1, 1970 00:00 GMT/UTC, and -0500 represents the timezone offset from GMT in 24-hour time. Negatives milliseconds are treated as dates before January 1, 1970. - *NOTE* NSDate objects do not have timezones, and you should never change an actual date value based on a + *NOTE *NSDate objects do not have timezones, and you should never change an actual date value based on a timezone offset. However, timezones are important when presenting dates to the user. Therefore, If an offset is present in the ASP.NET string (it should be), we actually ignore the offset portion because we want to store the actual date value in its raw form, without any pollution of timezone information. @@ -81,7 +81,7 @@ Where 1112715000000 is the number of milliseconds since January 1, 1970 00:00 GMT/UTC, and +0000 is the timezone offset from GMT in 24-hour time. - *NOTE* GMT (+0000) is assumed otherwise specified via setTimeZone: + *NOTE *GMT (+0000) is assumed otherwise specified via setTimeZone: @param date An NSDate @return The ASP.NET style string, /Date(1112715000000-0500)/ diff --git a/Code/Support/RKDotNetDateFormatter.m b/Code/Support/RKDotNetDateFormatter.m index 20685ef033..ff5c28b21e 100644 --- a/Code/Support/RKDotNetDateFormatter.m +++ b/Code/Support/RKDotNetDateFormatter.m @@ -27,24 +27,27 @@ NSTimeInterval secondsFromMilliseconds(NSTimeInterval millisecs); NSTimeInterval millisecondsFromSeconds(NSTimeInterval seconds); -@interface RKDotNetDateFormatter() +@interface RKDotNetDateFormatter () - (NSString *)millisecondsFromString:(NSString *)string; @end @implementation RKDotNetDateFormatter -+ (RKDotNetDateFormatter *)dotNetDateFormatter { ++ (RKDotNetDateFormatter *)dotNetDateFormatter +{ return [RKDotNetDateFormatter dotNetDateFormatterWithTimeZone:nil]; } -+ (RKDotNetDateFormatter *)dotNetDateFormatterWithTimeZone:(NSTimeZone *)newTimeZone { ++ (RKDotNetDateFormatter *)dotNetDateFormatterWithTimeZone:(NSTimeZone *)newTimeZone +{ RKDotNetDateFormatter *formatter = [[[RKDotNetDateFormatter alloc] init] autorelease]; if (newTimeZone) formatter.timeZone = newTimeZone; return formatter; } -- (NSDate *)dateFromString:(NSString *)string { +- (NSDate *)dateFromString:(NSString *)string +{ NSString *milliseconds = [self millisecondsFromString:string]; if (!milliseconds) { RKLogError(@"Attempted to interpret an invalid .NET date string: %@", string); @@ -55,7 +58,8 @@ - (NSDate *)dateFromString:(NSString *)string { } -- (NSString *)stringFromDate:(NSDate *)date { +- (NSString *)stringFromDate:(NSDate *)date +{ if (!date) { RKLogError(@"Attempted to represent an invalid date: %@", date); return nil; @@ -65,14 +69,16 @@ - (NSString *)stringFromDate:(NSDate *)date { return [NSString stringWithFormat:@"/Date(%1.0lf%@)/", milliseconds, timeZoneOffset]; } -- (BOOL)getObjectValue:(id *)outValue forString:(NSString *)string errorDescription:(NSString **)error { +- (BOOL)getObjectValue:(id *)outValue forString:(NSString *)string errorDescription:(NSString **)error +{ NSDate *date = [self dateFromString:string]; if (outValue) *outValue = date; return (date != nil); } -- (id)init { +- (id)init +{ self = [super init]; if (self) { self.locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]; @@ -85,13 +91,15 @@ - (id)init { } -- (void)dealloc { +- (void)dealloc +{ [dotNetExpression release]; [super dealloc]; } -- (NSString *)millisecondsFromString:(NSString *)string { +- (NSString *)millisecondsFromString:(NSString *)string +{ if (!string) return nil; NSTextCheckingResult *match = [dotNetExpression firstMatchInString:string options:NSMatchingCompleted range:NSMakeRange(0, [string length])]; @@ -118,7 +126,7 @@ NSTimeInterval secondsFromMilliseconds(NSTimeInterval millisecs) { NSTimeInterval millisecondsFromSeconds(NSTimeInterval seconds) { - return seconds * 1000.f; + return seconds *1000.f; } #endif diff --git a/Code/Support/RKErrors.h b/Code/Support/RKErrors.h index 8e279463f7..c9ce1f88f0 100644 --- a/Code/Support/RKErrors.h +++ b/Code/Support/RKErrors.h @@ -23,7 +23,7 @@ /** @name Error Domain & Codes */ // The error domain for RestKit generated errors -extern NSString* const RKErrorDomain; +extern NSString * const RKErrorDomain; typedef enum { RKObjectLoaderRemoteSystemError = 1, @@ -39,7 +39,7 @@ typedef enum { The key RestKit generated errors will appear at within an NSNotification indicating an error */ -extern NSString* const RKErrorNotificationErrorKey; +extern NSString * const RKErrorNotificationErrorKey; /** When RestKit constructs an NSError object from one or more RKErrorMessage @@ -50,4 +50,4 @@ extern NSString* const RKErrorNotificationErrorKey; @see RKObjectMappingResult */ -extern NSString* const RKObjectMapperErrorObjectsKey; +extern NSString * const RKObjectMapperErrorObjectsKey; diff --git a/Code/Support/RKErrors.m b/Code/Support/RKErrors.m index a6a790e7d4..2d308c2915 100644 --- a/Code/Support/RKErrors.m +++ b/Code/Support/RKErrors.m @@ -20,7 +20,7 @@ #import "RKErrors.h" -NSString* const RKErrorDomain = @"org.restkit.RestKit.ErrorDomain"; +NSString * const RKErrorDomain = @"org.restkit.RestKit.ErrorDomain"; -NSString* const RKObjectMapperErrorObjectsKey = @"RKObjectMapperErrorObjectsKey"; -NSString* const RKErrorNotificationErrorKey = @"error"; +NSString * const RKObjectMapperErrorObjectsKey = @"RKObjectMapperErrorObjectsKey"; +NSString * const RKErrorNotificationErrorKey = @"error"; diff --git a/Code/Support/RKLog.h b/Code/Support/RKLog.h index 0bb6b456a1..0f86e2e1aa 100644 --- a/Code/Support/RKLog.h +++ b/Code/Support/RKLog.h @@ -136,7 +136,7 @@ lcl_configure_by_name("App", level); @finally { \ lcl_configure_by_component(_component, _currentLevel); \ } \ - } while(false); + } while (false); /** Temporarily turns off logging for the given logging component during execution of the block. diff --git a/Code/Support/RKLog.m b/Code/Support/RKLog.m index ca5b06c9da..b58b209c22 100644 --- a/Code/Support/RKLog.m +++ b/Code/Support/RKLog.m @@ -68,7 +68,7 @@ void RKLogConfigureFromEnvironment(void) NSString *logComponent = [envVarName stringByReplacingOccurrencesOfString:logComponentPrefix withString:@""]; logComponent = [logComponent stringByReplacingOccurrencesOfString:@"." withString:@"/"]; - const char* log_component_c_str = [logComponent cStringUsingEncoding:NSUTF8StringEncoding]; + const char *log_component_c_str = [logComponent cStringUsingEncoding:NSUTF8StringEncoding]; int log_level_int = RKLogLevelForString(logLevel, envVarName); RKLogConfigureByName(log_component_c_str, log_level_int); } @@ -165,7 +165,7 @@ void RKLogIntegerAsBinary(NSUInteger bitMask) { NSMutableString *string = [NSMutableString string]; do { [string appendString:(((NSUInteger)bitMask & bit) ? @"1" : @"0")]; - } while ( bit >>= 1 ); - - NSLog(@"Value of %ld in binary: %@", (long) bitMask, string); + } while (bit >>= 1); + + NSLog(@"Value of %ld in binary: %@", (long)bitMask, string); } diff --git a/Code/Support/RKMIMETypes.h b/Code/Support/RKMIMETypes.h index 7cfdbaa300..79a228866f 100644 --- a/Code/Support/RKMIMETypes.h +++ b/Code/Support/RKMIMETypes.h @@ -23,13 +23,13 @@ */ /// MIME Type application/json -extern NSString* const RKMIMETypeJSON; +extern NSString * const RKMIMETypeJSON; /// MIME Type application/x-www-form-urlencoded -extern NSString* const RKMIMETypeFormURLEncoded; +extern NSString * const RKMIMETypeFormURLEncoded; /// MIME Type application/xml -extern NSString* const RKMIMETypeXML; +extern NSString * const RKMIMETypeXML; /// MIME Type text/xml -extern NSString* const RKMIMETypeTextXML; +extern NSString * const RKMIMETypeTextXML; diff --git a/Code/Support/RKMIMETypes.m b/Code/Support/RKMIMETypes.m index 818c21ec75..7d67a48696 100644 --- a/Code/Support/RKMIMETypes.m +++ b/Code/Support/RKMIMETypes.m @@ -20,7 +20,7 @@ #import "RKMIMETypes.h" -NSString* const RKMIMETypeJSON = @"application/json"; -NSString* const RKMIMETypeFormURLEncoded = @"application/x-www-form-urlencoded"; -NSString* const RKMIMETypeXML = @"application/xml"; -NSString* const RKMIMETypeTextXML = @"text/xml"; +NSString * const RKMIMETypeJSON = @"application/json"; +NSString * const RKMIMETypeFormURLEncoded = @"application/x-www-form-urlencoded"; +NSString * const RKMIMETypeXML = @"application/xml"; +NSString * const RKMIMETypeTextXML = @"text/xml"; diff --git a/Code/Support/RKMutableBlockDictionary.m b/Code/Support/RKMutableBlockDictionary.m index a2dbbf58b1..c367f1699f 100644 --- a/Code/Support/RKMutableBlockDictionary.m +++ b/Code/Support/RKMutableBlockDictionary.m @@ -36,14 +36,16 @@ @implementation RKMutableBlockDictionaryBlockValue @synthesize executionBlock = _executionBlock; -+ (id)valueWithBlock:(RKMutableBlockDictionaryValueBlock)executionBlock { - RKMutableBlockDictionaryBlockValue* value = [[self new] autorelease]; ++ (id)valueWithBlock:(RKMutableBlockDictionaryValueBlock)executionBlock +{ + RKMutableBlockDictionaryBlockValue *value = [[self new] autorelease]; value.executionBlock = executionBlock; return value; } -- (void)setExecutionBlock:(RKMutableBlockDictionaryValueBlock)executionBlock { +- (void)setExecutionBlock:(RKMutableBlockDictionaryValueBlock)executionBlock +{ if (_executionBlock) { Block_release(_executionBlock); _executionBlock = nil; @@ -51,7 +53,8 @@ - (void)setExecutionBlock:(RKMutableBlockDictionaryValueBlock)executionBlock { _executionBlock = Block_copy(executionBlock); } -- (void)dealloc { +- (void)dealloc +{ if (_executionBlock) { Block_release(_executionBlock); _executionBlock = nil; @@ -63,11 +66,13 @@ - (void)dealloc { @implementation RKMutableBlockDictionary -- (id)init { +- (id)init +{ return [self initWithCapacity:0]; } -- (id)initWithCapacity:(NSUInteger)capacity { +- (id)initWithCapacity:(NSUInteger)capacity +{ self = [super init]; if (self != nil) { _mutableDictionary = [[NSMutableDictionary alloc] initWithCapacity:capacity]; @@ -76,41 +81,50 @@ - (id)initWithCapacity:(NSUInteger)capacity { return self; } -- (void)dealloc { +- (void)dealloc +{ [_mutableDictionary release]; [super dealloc]; } -- (id)copy { +- (id)copy +{ return [self mutableCopy]; } -- (void)setObject:(id)anObject forKey:(id)aKey { +- (void)setObject:(id)anObject forKey:(id)aKey +{ [_mutableDictionary setObject:anObject forKey:aKey]; } -- (void)removeObjectForKey:(id)aKey { +- (void)removeObjectForKey:(id)aKey +{ [_mutableDictionary removeObjectForKey:aKey]; } -- (NSUInteger)count { +- (NSUInteger)count +{ return [_mutableDictionary count]; } -- (id)objectForKey:(id)aKey { +- (id)objectForKey:(id)aKey +{ return [_mutableDictionary objectForKey:aKey]; } -- (NSEnumerator *)keyEnumerator { +- (NSEnumerator *)keyEnumerator +{ return [_mutableDictionary keyEnumerator]; } -- (void)setValueWithBlock:(id (^)())block forKey:(NSString *)key { - RKMutableBlockDictionaryBlockValue* blockValue = [RKMutableBlockDictionaryBlockValue valueWithBlock:block]; +- (void)setValueWithBlock:(id (^)())block forKey:(NSString *)key +{ + RKMutableBlockDictionaryBlockValue *blockValue = [RKMutableBlockDictionaryBlockValue valueWithBlock:block]; [self setObject:blockValue forKey:key]; } -- (id)valueForKey:(NSString *)key { +- (id)valueForKey:(NSString *)key +{ id value = [self objectForKey:key]; if (value) { if ([value isKindOfClass:[RKMutableBlockDictionaryBlockValue class]]) { @@ -124,7 +138,8 @@ - (id)valueForKey:(NSString *)key { return nil; } -- (id)valueForKeyPath:(NSString *)keyPath { +- (id)valueForKeyPath:(NSString *)keyPath +{ id value = [super valueForKeyPath:keyPath]; if (value) { if ([value isKindOfClass:[RKMutableBlockDictionaryBlockValue class]]) { @@ -138,7 +153,8 @@ - (id)valueForKeyPath:(NSString *)keyPath { return nil; } -- (void)setValue:(id)value forKey:(NSString *)key { +- (void)setValue:(id)value forKey:(NSString *)key +{ [self setObject:value forKey:key]; } diff --git a/Code/Support/RKPathMatcher.h b/Code/Support/RKPathMatcher.h index 53c5ecfb96..c79e02290a 100755 --- a/Code/Support/RKPathMatcher.h +++ b/Code/Support/RKPathMatcher.h @@ -33,13 +33,8 @@ @see RKMakePathWithObject @see RKRouter */ -@interface RKPathMatcher : NSObject { -@private - SOCPattern *socPattern_; - NSString *sourcePath_; - NSString *rootPath_; - NSDictionary *queryParameters_; -} +@interface RKPathMatcher : NSObject + @property (copy, readonly) NSDictionary *queryParameters; /** @@ -49,7 +44,7 @@ @param pathString The string to evaluate and parse, such as /districts/tx/upper/?apikey=GC5512354 @return An instantiated RKPathMatcher without an established pattern. */ -+(RKPathMatcher *)matcherWithPath:(NSString *)pathString; ++ (RKPathMatcher *)matcherWithPath:(NSString *)pathString; /** Determines if the path string matches the provided pattern, and yields a dictionary with the resulting @@ -57,11 +52,11 @@ Pattern strings should include encoded parameter keys, delimited by a single colon at the beginning of the key name. - *NOTE 1* - Numerous colon-encoded parameter keys can be joined in a long pattern, but each key must be + *NOTE 1 *- Numerous colon-encoded parameter keys can be joined in a long pattern, but each key must be separated by at least one unmapped character. For instance, /:key1:key2:key3/ is invalid, whereas /:key1/:key2/:key3/ is acceptable. - *NOTE 2* - The pattern matcher supports KVM, so :key1.otherKey normally resolves as it would in any other KVM + *NOTE 2 *- The pattern matcher supports KVM, so :key1.otherKey normally resolves as it would in any other KVM situation, ... otherKey is a sub-key on a the object represented by key1. This presents problems in circumstances where you might want to build a pattern like /:filename.json, where the dot isn't intended as a sub-key on the filename, but rather part of the json static string. In these instances, you need to escape the dot with two backslashes, like so: @@ -79,11 +74,11 @@ matchesPath:tokenizeQueryStrings:parsedArguments: Patterns should include encoded parameter keys, delimited by a single colon at the beginning of the key name. - *NOTE 1* - Numerous colon-encoded parameter keys can be joined in a long pattern, but each key must be + *NOTE 1 *- Numerous colon-encoded parameter keys can be joined in a long pattern, but each key must be separated by at least one unmapped character. For instance, /:key1:key2:key3/ is invalid, whereas /:key1/:key2/:key3/ is acceptable. - *NOTE 2* - The pattern matcher supports KVM, so :key1.otherKey normally resolves as it would in any other KVM + *NOTE 2 *- The pattern matcher supports KVM, so :key1.otherKey normally resolves as it would in any other KVM situation, ... otherKey is a sub-key on a the object represented by key1. This presents problems in circumstances where you might want to build a pattern like /:filename.json, where the dot isn't intended as a sub-key on the filename, but rather part of the json static string. In these instances, you need to escape the dot with two backslashes, like so: @@ -92,7 +87,7 @@ @param patternString The pattern to use for evaluating, such as /:entityName/:stateID/:chamber/ @return An instantiated RKPathMatcher with an established pattern. */ -+(RKPathMatcher *)matcherWithPattern:(NSString *)patternString; ++ (RKPathMatcher *)matcherWithPattern:(NSString *)patternString; /** Determines if the provided resource path string matches a pattern, and yields a dictionary with the resulting diff --git a/Code/Support/RKPathMatcher.m b/Code/Support/RKPathMatcher.m index 4726f499c4..9f1fe940f0 100755 --- a/Code/Support/RKPathMatcher.m +++ b/Code/Support/RKPathMatcher.m @@ -45,30 +45,31 @@ BOOL RKPathUsesParentheticalParameters(NSString *path) { // NSString's stringByAddingPercentEscapes doesn't do a complete job (it ignores "/?&", among others) NSString *RKEncodeURLString(NSString *unencodedString) { - NSString * encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes( - NULL, - (CFStringRef)unencodedString, - NULL, - (CFStringRef)@"!*'();:@&=+$,/?%#[]", - kCFStringEncodingUTF8 ); + NSString *encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes( + NULL, + (CFStringRef)unencodedString, + NULL, + (CFStringRef)@"!*'();:@&=+$,/?%#[]", + kCFStringEncodingUTF8); return [encodedString autorelease]; } -@interface RKPathMatcher() -@property (nonatomic,retain) SOCPattern *socPattern; -@property (nonatomic,copy) NSString *sourcePath; -@property (nonatomic,copy) NSString *rootPath; -@property (copy,readwrite) NSDictionary *queryParameters; +@interface RKPathMatcher () +@property (nonatomic, retain) SOCPattern *socPattern; +@property (nonatomic, copy) NSString *sourcePath; +@property (nonatomic, copy) NSString *rootPath; +@property (copy, readwrite) NSDictionary *queryParameters; @end @implementation RKPathMatcher -@synthesize socPattern=socPattern_; -@synthesize sourcePath=sourcePath_; -@synthesize rootPath=rootPath_; -@synthesize queryParameters=queryParameters_; - -- (id)copyWithZone:(NSZone *)zone { - RKPathMatcher* copy = [[[self class] allocWithZone:zone] init]; +@synthesize socPattern = socPattern_; +@synthesize sourcePath = sourcePath_; +@synthesize rootPath = rootPath_; +@synthesize queryParameters = queryParameters_; + +- (id)copyWithZone:(NSZone *)zone +{ + RKPathMatcher *copy = [[[self class] allocWithZone:zone] init]; copy.socPattern = self.socPattern; copy.sourcePath = self.sourcePath; copy.rootPath = self.rootPath; @@ -77,7 +78,8 @@ - (id)copyWithZone:(NSZone *)zone { return copy; } -- (void)dealloc { +- (void)dealloc +{ self.socPattern = nil; self.sourcePath = nil; self.rootPath = nil; @@ -85,7 +87,8 @@ - (void)dealloc { [super dealloc]; } -+(RKPathMatcher *)matcherWithPattern:(NSString *)patternString { ++ (RKPathMatcher *)matcherWithPattern:(NSString *)patternString +{ NSAssert(patternString != NULL, @"Pattern string must not be empty in order to perform pattern matching."); patternString = RKPathPatternFindAndReplaceParensWithColons(patternString); RKPathMatcher *matcher = [[[RKPathMatcher alloc] init] autorelease]; @@ -93,19 +96,22 @@ +(RKPathMatcher *)matcherWithPattern:(NSString *)patternString { return matcher; } -+(RKPathMatcher *)matcherWithPath:(NSString *)pathString { ++ (RKPathMatcher *)matcherWithPath:(NSString *)pathString +{ RKPathMatcher *matcher = [[[RKPathMatcher alloc] init] autorelease]; matcher.sourcePath = pathString; matcher.rootPath = pathString; return matcher; } -- (BOOL)matches { - NSAssert( (self.socPattern != NULL && self.rootPath != NULL) , @"Matcher is insufficiently configured. Before attempting pattern matching, you must provide a path string and a pattern to match it against."); +- (BOOL)matches +{ + NSAssert( (self.socPattern != NULL && self.rootPath != NULL), @"Matcher is insufficiently configured. Before attempting pattern matching, you must provide a path string and a pattern to match it against."); return [self.socPattern stringMatches:self.rootPath]; } -- (BOOL)bifurcateSourcePathFromQueryParameters { +- (BOOL)bifurcateSourcePathFromQueryParameters +{ NSArray *components = [self.sourcePath componentsSeparatedByString:@"?"]; if ([components count] > 1) { self.rootPath = [components objectAtIndex:0]; @@ -115,7 +121,8 @@ - (BOOL)bifurcateSourcePathFromQueryParameters { return NO; } -- (BOOL)itMatchesAndHasParsedArguments:(NSDictionary **)arguments tokenizeQueryStrings:(BOOL)shouldTokenize { +- (BOOL)itMatchesAndHasParsedArguments:(NSDictionary **)arguments tokenizeQueryStrings:(BOOL)shouldTokenize +{ NSAssert(self.socPattern != NULL, @"Matcher has no established pattern. Instantiate it using matcherWithPattern: before attempting a pattern match."); NSMutableDictionary *argumentsCollection = [NSMutableDictionary dictionary]; if ([self bifurcateSourcePathFromQueryParameters]) { @@ -135,30 +142,34 @@ - (BOOL)itMatchesAndHasParsedArguments:(NSDictionary **)arguments tokenizeQueryS return YES; } -- (BOOL)matchesPattern:(NSString *)patternString tokenizeQueryStrings:(BOOL)shouldTokenize parsedArguments:(NSDictionary **)arguments { +- (BOOL)matchesPattern:(NSString *)patternString tokenizeQueryStrings:(BOOL)shouldTokenize parsedArguments:(NSDictionary **)arguments +{ NSAssert(patternString != NULL, @"Pattern string must not be empty in order to perform patterm matching."); patternString = RKPathPatternFindAndReplaceParensWithColons(patternString); self.socPattern = [SOCPattern patternWithString:patternString]; return [self itMatchesAndHasParsedArguments:arguments tokenizeQueryStrings:shouldTokenize]; } -- (BOOL)matchesPath:(NSString *)sourceString tokenizeQueryStrings:(BOOL)shouldTokenize parsedArguments:(NSDictionary **)arguments { +- (BOOL)matchesPath:(NSString *)sourceString tokenizeQueryStrings:(BOOL)shouldTokenize parsedArguments:(NSDictionary **)arguments +{ self.sourcePath = sourceString; self.rootPath = sourceString; return [self itMatchesAndHasParsedArguments:arguments tokenizeQueryStrings:shouldTokenize]; } -- (NSString *)pathFromObject:(id)object { +- (NSString *)pathFromObject:(id)object +{ return [self pathFromObject:object addingEscapes:YES]; } -- (NSString *)pathFromObject:(id)object addingEscapes:(BOOL)addEscapes { +- (NSString *)pathFromObject:(id)object addingEscapes:(BOOL)addEscapes +{ NSAssert(self.socPattern != NULL, @"Matcher has no established pattern. Instantiate it using matcherWithPattern: before calling pathFromObject:"); NSAssert(object != NULL, @"Object provided is invalid; cannot create a path from a NULL object"); - NSString *(^encoderBlock)(NSString* interpolatedString) = nil; + NSString *(^encoderBlock)(NSString *interpolatedString) = nil; if (addEscapes) - encoderBlock = ^NSString *(NSString* interpolatedString) { + encoderBlock = ^NSString *(NSString *interpolatedString) { return RKEncodeURLString(interpolatedString); }; NSString *path = [self.socPattern stringFromObject:object withBlock:encoderBlock]; diff --git a/Code/Support/RKPortCheck.m b/Code/Support/RKPortCheck.m index 0d95bc6421..c8b9029813 100644 --- a/Code/Support/RKPortCheck.m +++ b/Code/Support/RKPortCheck.m @@ -34,7 +34,7 @@ - (id)initWithHost:(NSString *)hostNameOrIPAddress port:(NSUInteger)port _port = port; struct sockaddr_in sa; - char *hostNameOrIPAddressCString = (char *) [hostNameOrIPAddress UTF8String]; + char *hostNameOrIPAddressCString = (char *)[hostNameOrIPAddress UTF8String]; int result = inet_pton(AF_INET, hostNameOrIPAddressCString, &(sa.sin_addr)); if (result != 0) { // IP Address @@ -78,7 +78,7 @@ - (void)run } // Try to connect to the port - _open = (connect(sd,(struct sockaddr *) &_remote_saddr, sizeof(_remote_saddr)) == 0); + _open = (connect(sd, (struct sockaddr *)&_remote_saddr, sizeof(_remote_saddr)) == 0); if (_open) { close(sd); diff --git a/Code/Support/RKSearchEngine.m b/Code/Support/RKSearchEngine.m index a6bfa70808..7423894404 100644 --- a/Code/Support/RKSearchEngine.m +++ b/Code/Support/RKSearchEngine.m @@ -66,7 +66,7 @@ - (NSArray *)tokenizeOrCollect:(NSString *)string return [NSArray arrayWithObject:string]; } -- (NSArray *)searchWithTerms:(NSArray*)searchTerms onProperties:(NSArray *)properties inCollection:(NSArray *)collection compoundSelector:(SEL)selector +- (NSArray *)searchWithTerms:(NSArray *)searchTerms onProperties:(NSArray *)properties inCollection:(NSArray *)collection compoundSelector:(SEL)selector { NSPredicate *searchPredicate = nil; diff --git a/Code/Testing/RKMappingTest.h b/Code/Testing/RKMappingTest.h index 4d62375762..ecbd823260 100644 --- a/Code/Testing/RKMappingTest.h +++ b/Code/Testing/RKMappingTest.h @@ -140,7 +140,7 @@ /** The object mapping under test. */ -@property(nonatomic, strong, readonly) RKObjectMapping *mapping; +@property (nonatomic, strong, readonly) RKObjectMapping *mapping; /** A key path to apply to the source object to specify the location of the root @@ -149,12 +149,12 @@ **Default**: nil */ -@property(nonatomic, copy) NSString *rootKeyPath; +@property (nonatomic, copy) NSString *rootKeyPath; /** The source object being mapped from. */ -@property(nonatomic, strong, readonly) id sourceObject; +@property (nonatomic, strong, readonly) id sourceObject; /** The destionation object being mapped to. @@ -165,7 +165,7 @@ @see [RKObjectMapping mappableObjectForData:] */ -@property(nonatomic, strong, readonly) id destinationObject; +@property (nonatomic, strong, readonly) id destinationObject; /** A Boolean value that determines if expectations should be verified immediately @@ -173,6 +173,6 @@ **Default**: NO */ -@property(nonatomic, assign) BOOL verifiesOnExpect; +@property (nonatomic, assign) BOOL verifiesOnExpect; @end diff --git a/Code/Testing/RKMappingTest.m b/Code/Testing/RKMappingTest.m index 4b015a7371..e209054bbd 100644 --- a/Code/Testing/RKMappingTest.m +++ b/Code/Testing/RKMappingTest.m @@ -47,7 +47,8 @@ @implementation RKMappingTestEvent @synthesize value; @synthesize mapping; -+ (RKMappingTestEvent *)eventWithMapping:(RKObjectAttributeMapping *)mapping value:(id)value { ++ (RKMappingTestEvent *)eventWithMapping:(RKObjectAttributeMapping *)mapping value:(id)value +{ RKMappingTestEvent *event = [RKMappingTestEvent new]; event.value = value; event.mapping = mapping; @@ -55,15 +56,18 @@ + (RKMappingTestEvent *)eventWithMapping:(RKObjectAttributeMapping *)mapping val return event; } -- (NSString *)sourceKeyPath { +- (NSString *)sourceKeyPath +{ return self.mapping.sourceKeyPath; } -- (NSString *)destinationKeyPath { +- (NSString *)destinationKeyPath +{ return self.mapping.destinationKeyPath; } -- (NSString *)description { +- (NSString *)description +{ return [NSString stringWithFormat:@"%@: mapped sourceKeyPath '%@' => destinationKeyPath '%@' with value: %@", [self class], self.sourceKeyPath, self.destinationKeyPath, self.value]; } @@ -97,15 +101,18 @@ @implementation RKMappingTest @synthesize verifiesOnExpect = _verifiesOnExpect; @synthesize performedMapping = _performedMapping; -+ (RKMappingTest *)testForMapping:(RKObjectMapping *)mapping object:(id)sourceObject { ++ (RKMappingTest *)testForMapping:(RKObjectMapping *)mapping object:(id)sourceObject +{ return [[self alloc] initWithMapping:mapping sourceObject:sourceObject destinationObject:nil]; } -+ (RKMappingTest *)testForMapping:(RKObjectMapping *)mapping sourceObject:(id)sourceObject destinationObject:(id)destinationObject { ++ (RKMappingTest *)testForMapping:(RKObjectMapping *)mapping sourceObject:(id)sourceObject destinationObject:(id)destinationObject +{ return [[self alloc] initWithMapping:mapping sourceObject:sourceObject destinationObject:destinationObject]; } -- (id)initWithMapping:(RKObjectMapping *)mapping sourceObject:(id)sourceObject destinationObject:(id)destinationObject { +- (id)initWithMapping:(RKObjectMapping *)mapping sourceObject:(id)sourceObject destinationObject:(id)destinationObject +{ NSAssert(sourceObject != nil, @"Cannot perform a mapping operation without a sourceObject object"); NSAssert(mapping != nil, @"Cannot perform a mapping operation without a mapping"); @@ -123,7 +130,8 @@ - (id)initWithMapping:(RKObjectMapping *)mapping sourceObject:(id)sourceObject d return self; } -- (void)addExpectation:(RKMappingTestExpectation *)expectation { +- (void)addExpectation:(RKMappingTestExpectation *)expectation +{ [self.expectations addObject:expectation]; if (self.verifiesOnExpect) { @@ -132,19 +140,23 @@ - (void)addExpectation:(RKMappingTestExpectation *)expectation { } } -- (void)expectMappingFromKeyPath:(NSString *)sourceKeyPath toKeyPath:(NSString *)destinationKeyPath { +- (void)expectMappingFromKeyPath:(NSString *)sourceKeyPath toKeyPath:(NSString *)destinationKeyPath +{ [self addExpectation:[RKMappingTestExpectation expectationWithSourceKeyPath:sourceKeyPath destinationKeyPath:destinationKeyPath]]; } -- (void)expectMappingFromKeyPath:(NSString *)sourceKeyPath toKeyPath:(NSString *)destinationKeyPath withValue:(id)value { +- (void)expectMappingFromKeyPath:(NSString *)sourceKeyPath toKeyPath:(NSString *)destinationKeyPath withValue:(id)value +{ [self addExpectation:[RKMappingTestExpectation expectationWithSourceKeyPath:sourceKeyPath destinationKeyPath:destinationKeyPath value:value]]; } -- (void)expectMappingFromKeyPath:(NSString *)sourceKeyPath toKeyPath:(NSString *)destinationKeyPath passingTest:(BOOL (^)(RKObjectAttributeMapping *mapping, id value))evaluationBlock { +- (void)expectMappingFromKeyPath:(NSString *)sourceKeyPath toKeyPath:(NSString *)destinationKeyPath passingTest:(BOOL (^)(RKObjectAttributeMapping *mapping, id value))evaluationBlock +{ [self addExpectation:[RKMappingTestExpectation expectationWithSourceKeyPath:sourceKeyPath destinationKeyPath:destinationKeyPath evaluationBlock:evaluationBlock]]; } -- (RKMappingTestEvent *)eventMatchingKeyPathsForExpectation:(RKMappingTestExpectation *)expectation { +- (RKMappingTestEvent *)eventMatchingKeyPathsForExpectation:(RKMappingTestExpectation *)expectation +{ for (RKMappingTestEvent *event in self.events) { if ([event.sourceKeyPath isEqualToString:expectation.sourceKeyPath] && [event.destinationKeyPath isEqualToString:expectation.destinationKeyPath]) { return event; @@ -154,7 +166,8 @@ - (RKMappingTestEvent *)eventMatchingKeyPathsForExpectation:(RKMappingTestExpect return nil; } -- (BOOL)event:(RKMappingTestEvent *)event satisfiesExpectation:(RKMappingTestExpectation *)expectation { +- (BOOL)event:(RKMappingTestEvent *)event satisfiesExpectation:(RKMappingTestExpectation *)expectation +{ if (expectation.evaluationBlock) { // Let the expectation block evaluate the match return expectation.evaluationBlock(event.mapping, event.value); @@ -167,7 +180,8 @@ - (BOOL)event:(RKMappingTestEvent *)event satisfiesExpectation:(RKMappingTestExp return YES; } -- (void)performMapping { +- (void)performMapping +{ NSAssert(self.mapping.objectClass, @"Cannot test a mapping that does not have a destination objectClass"); // Ensure repeated invocations of verify only result in a single mapping operation @@ -189,7 +203,8 @@ - (void)performMapping { } } -- (void)verifyExpectation:(RKMappingTestExpectation *)expectation { +- (void)verifyExpectation:(RKMappingTestExpectation *)expectation +{ RKMappingTestEvent *event = [self eventMatchingKeyPathsForExpectation:expectation]; if (event) { // Found a matching event, check if it satisfies the expectation @@ -204,7 +219,8 @@ - (void)verifyExpectation:(RKMappingTestExpectation *)expectation { } } -- (void)verify { +- (void)verify +{ [self performMapping]; for (RKMappingTestExpectation *expectation in self.expectations) { @@ -214,15 +230,18 @@ - (void)verify { #pragma mark - RKObjecMappingOperationDelegate -- (void)addEvent:(RKMappingTestEvent *)event { +- (void)addEvent:(RKMappingTestEvent *)event +{ [self.events addObject:event]; } -- (void)objectMappingOperation:(RKObjectMappingOperation *)operation didSetValue:(id)value forKeyPath:(NSString *)keyPath usingMapping:(RKObjectAttributeMapping *)mapping { +- (void)objectMappingOperation:(RKObjectMappingOperation *)operation didSetValue:(id)value forKeyPath:(NSString *)keyPath usingMapping:(RKObjectAttributeMapping *)mapping +{ [self addEvent:[RKMappingTestEvent eventWithMapping:mapping value:value]]; } -- (void)objectMappingOperation:(RKObjectMappingOperation *)operation didNotSetUnchangedValue:(id)value forKeyPath:(NSString *)keyPath usingMapping:(RKObjectAttributeMapping *)mapping { +- (void)objectMappingOperation:(RKObjectMappingOperation *)operation didNotSetUnchangedValue:(id)value forKeyPath:(NSString *)keyPath usingMapping:(RKObjectAttributeMapping *)mapping +{ [self addEvent:[RKMappingTestEvent eventWithMapping:mapping value:value]]; } diff --git a/Code/Testing/RKMappingTestExpectation.m b/Code/Testing/RKMappingTestExpectation.m index 7613ce3959..cbad788e6d 100644 --- a/Code/Testing/RKMappingTestExpectation.m +++ b/Code/Testing/RKMappingTestExpectation.m @@ -23,7 +23,8 @@ @implementation RKMappingTestExpectation @synthesize value; @synthesize evaluationBlock; -+ (RKMappingTestExpectation *)expectationWithSourceKeyPath:(NSString *)sourceKeyPath destinationKeyPath:(NSString *)destinationKeyPath { ++ (RKMappingTestExpectation *)expectationWithSourceKeyPath:(NSString *)sourceKeyPath destinationKeyPath:(NSString *)destinationKeyPath +{ RKMappingTestExpectation *expectation = [self new]; expectation.sourceKeyPath = sourceKeyPath; expectation.destinationKeyPath = destinationKeyPath; @@ -31,7 +32,8 @@ + (RKMappingTestExpectation *)expectationWithSourceKeyPath:(NSString *)sourceKey return expectation; } -+ (RKMappingTestExpectation *)expectationWithSourceKeyPath:(NSString *)sourceKeyPath destinationKeyPath:(NSString *)destinationKeyPath value:(id)value { ++ (RKMappingTestExpectation *)expectationWithSourceKeyPath:(NSString *)sourceKeyPath destinationKeyPath:(NSString *)destinationKeyPath value:(id)value +{ RKMappingTestExpectation *expectation = [self new]; expectation.sourceKeyPath = sourceKeyPath; expectation.destinationKeyPath = destinationKeyPath; @@ -40,7 +42,8 @@ + (RKMappingTestExpectation *)expectationWithSourceKeyPath:(NSString *)sourceKey return expectation; } -+ (RKMappingTestExpectation *)expectationWithSourceKeyPath:(NSString *)sourceKeyPath destinationKeyPath:(NSString *)destinationKeyPath evaluationBlock:(BOOL (^)(RKObjectAttributeMapping *mapping, id value))testBlock { ++ (RKMappingTestExpectation *)expectationWithSourceKeyPath:(NSString *)sourceKeyPath destinationKeyPath:(NSString *)destinationKeyPath evaluationBlock:(BOOL (^)(RKObjectAttributeMapping *mapping, id value))testBlock +{ RKMappingTestExpectation *expectation = [self new]; expectation.sourceKeyPath = sourceKeyPath; expectation.destinationKeyPath = destinationKeyPath; @@ -49,12 +52,14 @@ + (RKMappingTestExpectation *)expectationWithSourceKeyPath:(NSString *)sourceKey return expectation; } -- (NSString *)mappingDescription { +- (NSString *)mappingDescription +{ return [NSString stringWithFormat:@"expected sourceKeyPath '%@' to map to destinationKeyPath '%@'", self.sourceKeyPath, self.destinationKeyPath]; } -- (NSString *)description { +- (NSString *)description +{ if (self.value) { return [NSString stringWithFormat:@"expected sourceKeyPath '%@' to map to destinationKeyPath '%@' with %@ value '%@'", self.sourceKeyPath, self.destinationKeyPath, [self.value class], self.value]; diff --git a/Code/Testing/RKTableControllerTestDelegate.h b/Code/Testing/RKTableControllerTestDelegate.h index ad70ef4d33..3ddcc291c9 100644 --- a/Code/Testing/RKTableControllerTestDelegate.h +++ b/Code/Testing/RKTableControllerTestDelegate.h @@ -12,9 +12,9 @@ @interface RKAbstractTableControllerTestDelegate : NSObject -@property(nonatomic, readonly, getter = isCancelled) BOOL cancelled; -@property(nonatomic, assign) NSTimeInterval timeout; -@property(nonatomic, assign) BOOL awaitingResponse; +@property (nonatomic, readonly, getter = isCancelled) BOOL cancelled; +@property (nonatomic, assign) NSTimeInterval timeout; +@property (nonatomic, assign) BOOL awaitingResponse; + (id)tableControllerDelegate; - (void)waitForLoad; diff --git a/Code/Testing/RKTableControllerTestDelegate.m b/Code/Testing/RKTableControllerTestDelegate.m index 31332e7593..5a113bbbc2 100644 --- a/Code/Testing/RKTableControllerTestDelegate.m +++ b/Code/Testing/RKTableControllerTestDelegate.m @@ -17,25 +17,28 @@ @implementation RKAbstractTableControllerTestDelegate @synthesize awaitingResponse = _awaitingResponse; @synthesize cancelled = _cancelled; -+ (id)tableControllerDelegate { ++ (id)tableControllerDelegate +{ return [[self new] autorelease]; } -- (id)init { +- (id)init +{ self = [super init]; if (self) { _timeout = 1.0; _awaitingResponse = NO; _cancelled = NO; } - + return self; } -- (void)waitForLoad { +- (void)waitForLoad +{ _awaitingResponse = YES; NSDate *startDate = [NSDate date]; - + while (_awaitingResponse) { RKLogTrace(@"Awaiting response = %d", _awaitingResponse); [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; @@ -49,20 +52,24 @@ - (void)waitForLoad { #pragma RKTableControllerDelegate methods -- (void)tableControllerDidFinishLoad:(RKAbstractTableController *)tableController { +- (void)tableControllerDidFinishLoad:(RKAbstractTableController *)tableController +{ _awaitingResponse = NO; } -- (void)tableController:(RKAbstractTableController*)tableController didFailLoadWithError:(NSError *)error { +- (void)tableController:(RKAbstractTableController *)tableController didFailLoadWithError:(NSError *)error +{ _awaitingResponse = NO; } -- (void)tableControllerDidCancelLoad:(RKAbstractTableController *)tableController { +- (void)tableControllerDidCancelLoad:(RKAbstractTableController *)tableController +{ _awaitingResponse = NO; _cancelled = YES; } -- (void)tableControllerDidFinalizeLoad:(RKAbstractTableController *)tableController { +- (void)tableControllerDidFinalizeLoad:(RKAbstractTableController *)tableController +{ _awaitingResponse = NO; } @@ -81,31 +88,31 @@ - (void)tableController:(RKAbstractTableController *)tableController willLoadTab - (void)tableController:(RKAbstractTableController *)tableController didLoadTableWithObjectLoader:(RKObjectLoader *)objectLoader {} -- (void)tableController:(RKAbstractTableController*)tableController willBeginEditing:(id)object atIndexPath:(NSIndexPath*)indexPath +- (void)tableController:(RKAbstractTableController *)tableController willBeginEditing:(id)object atIndexPath:(NSIndexPath *)indexPath {} -- (void)tableController:(RKAbstractTableController*)tableController didEndEditing:(id)object atIndexPath:(NSIndexPath*)indexPath +- (void)tableController:(RKAbstractTableController *)tableController didEndEditing:(id)object atIndexPath:(NSIndexPath *)indexPath {} -- (void)tableController:(RKAbstractTableController*)tableController didInsertSection:(RKTableSection*)section atIndex:(NSUInteger)sectionIndex +- (void)tableController:(RKAbstractTableController *)tableController didInsertSection:(RKTableSection *)section atIndex:(NSUInteger)sectionIndex {} -- (void)tableController:(RKAbstractTableController*)tableController didRemoveSection:(RKTableSection*)section atIndex:(NSUInteger)sectionIndex +- (void)tableController:(RKAbstractTableController *)tableController didRemoveSection:(RKTableSection *)section atIndex:(NSUInteger)sectionIndex {} -- (void)tableController:(RKAbstractTableController*)tableController didInsertObject:(id)object atIndexPath:(NSIndexPath*)indexPath +- (void)tableController:(RKAbstractTableController *)tableController didInsertObject:(id)object atIndexPath:(NSIndexPath *)indexPath {} -- (void)tableController:(RKAbstractTableController*)tableController didUpdateObject:(id)object atIndexPath:(NSIndexPath*)indexPath +- (void)tableController:(RKAbstractTableController *)tableController didUpdateObject:(id)object atIndexPath:(NSIndexPath *)indexPath {} -- (void)tableController:(RKAbstractTableController*)tableController didDeleteObject:(id)object atIndexPath:(NSIndexPath*)indexPath +- (void)tableController:(RKAbstractTableController *)tableController didDeleteObject:(id)object atIndexPath:(NSIndexPath *)indexPath {} -- (void)tableController:(RKAbstractTableController*)tableController willAddSwipeView:(UIView*)swipeView toCell:(UITableViewCell*)cell forObject:(id)object +- (void)tableController:(RKAbstractTableController *)tableController willAddSwipeView:(UIView *)swipeView toCell:(UITableViewCell *)cell forObject:(id)object {} -- (void)tableController:(RKAbstractTableController*)tableController willRemoveSwipeView:(UIView*)swipeView fromCell:(UITableViewCell*)cell forObject:(id)object +- (void)tableController:(RKAbstractTableController *)tableController willRemoveSwipeView:(UIView *)swipeView fromCell:(UITableViewCell *)cell forObject:(id)object {} - (void)tableController:(RKTableController *)tableController didLoadObjects:(NSArray *)objects inSection:(NSUInteger)sectionIndex @@ -114,7 +121,7 @@ - (void)tableController:(RKTableController *)tableController didLoadObjects:(NSA - (void)tableController:(RKAbstractTableController *)tableController willDisplayCell:(UITableViewCell *)cell forObject:(id)object atIndexPath:(NSIndexPath *)indexPath {} -- (void)tableController:(RKAbstractTableController *)tableController didSelectCell:(UITableViewCell *)cell forObject:(id)object atIndexPath:(NSIndexPath *)indexPath +- (void)tableController:(RKAbstractTableController *)tableController didSelectCell:(UITableViewCell *)cell forObject:(id)object atIndexPath:(NSIndexPath *)indexPath {} @end diff --git a/Code/Testing/RKTestFactory.m b/Code/Testing/RKTestFactory.m index 426261aa6f..de836c7a9a 100644 --- a/Code/Testing/RKTestFactory.m +++ b/Code/Testing/RKTestFactory.m @@ -78,7 +78,7 @@ - (void)defineDefaultFactories { [self defineFactory:RKTestFactoryDefaultNamesClient withBlock:^id { __block RKClient *client; - + RKLogSilenceComponentWhileExecutingBlock(lcl_cRestKitNetworkReachability, ^{ RKLogSilenceComponentWhileExecutingBlock(lcl_cRestKitSupport, ^{ client = [RKClient clientWithBaseURL:self.baseURL]; @@ -92,13 +92,13 @@ - (void)defineDefaultFactories [self defineFactory:RKTestFactoryDefaultNamesObjectManager withBlock:^id { __block RKObjectManager *objectManager; - + RKLogSilenceComponentWhileExecutingBlock(lcl_cRestKitNetworkReachability, ^{ RKLogSilenceComponentWhileExecutingBlock(lcl_cRestKitSupport, ^{ objectManager = [RKObjectManager managerWithBaseURL:self.baseURL]; RKObjectMappingProvider *mappingProvider = [self objectFromFactory:RKTestFactoryDefaultNamesMappingProvider]; objectManager.mappingProvider = mappingProvider; - + // Force reachability determination [objectManager.client.reachabilityObserver getFlags]; }); @@ -167,7 +167,7 @@ + (id)objectFromFactory:(NSString *)factoryName + (NSSet *)factoryNames { - return [NSSet setWithArray:[[RKTestFactory sharedFactory].factoryBlocks allKeys] ]; + return [NSSet setWithArray:[[RKTestFactory sharedFactory].factoryBlocks allKeys]]; } + (id)client @@ -206,7 +206,7 @@ + (void)setUp { [RKObjectManager setDefaultMappingQueue:dispatch_queue_create("org.restkit.ObjectMapping", DISPATCH_QUEUE_SERIAL)]; [RKObjectMapping setDefaultDateFormatters:nil]; - + // Delete the store if it exists NSString *path = [[RKDirectory applicationDataDirectory] stringByAppendingPathComponent:RKTestFactoryDefaultStoreFilename]; if ([[NSFileManager defaultManager] fileExistsAtPath:path]) { @@ -231,8 +231,8 @@ + (void)tearDown + (void)clearCacheDirectory { - NSError* error = nil; - NSString* cachePath = [RKDirectory cachesDirectory]; + NSError *error = nil; + NSString *cachePath = [RKDirectory cachesDirectory]; BOOL success = [[NSFileManager defaultManager] removeItemAtPath:cachePath error:&error]; if (success) { RKLogDebug(@"Cleared cache directory..."); diff --git a/Code/Testing/RKTestFixture.m b/Code/Testing/RKTestFixture.m index 3f689bac45..366082bd35 100644 --- a/Code/Testing/RKTestFixture.m +++ b/Code/Testing/RKTestFixture.m @@ -25,41 +25,49 @@ @implementation RKTestFixture -+ (NSBundle *)fixtureBundle { ++ (NSBundle *)fixtureBundle +{ NSAssert(fixtureBundle != nil, @"Bundle for fixture has not been set. Use setFixtureBundle: to set it."); return fixtureBundle; } -+ (void)setFixtureBundle:(NSBundle *)bundle { ++ (void)setFixtureBundle:(NSBundle *)bundle +{ NSAssert(bundle != nil, @"Bundle for fixture cannot be nil."); [bundle retain]; [fixtureBundle release]; fixtureBundle = bundle; } -+ (NSString *)pathForFixture:(NSString *)fixtureName { ++ (NSString *)pathForFixture:(NSString *)fixtureName +{ return [[self fixtureBundle] pathForResource:fixtureName ofType:nil]; } #if TARGET_OS_IPHONE -+ (UIImage *)imageWithContentsOfFixture:(NSString *)fixtureName { ++ (UIImage *)imageWithContentsOfFixture:(NSString *)fixtureName +{ return [[self fixtureBundle] imageWithContentsOfResource:fixtureName withExtension:nil]; } #endif -+ (NSString *)stringWithContentsOfFixture:(NSString *)fixtureName { ++ (NSString *)stringWithContentsOfFixture:(NSString *)fixtureName +{ return [[self fixtureBundle] stringWithContentsOfResource:fixtureName withExtension:nil encoding:NSUTF8StringEncoding]; } -+ (NSData *)dataWithContentsOfFixture:(NSString *)fixtureName { ++ (NSData *)dataWithContentsOfFixture:(NSString *)fixtureName +{ return [[self fixtureBundle] dataWithContentsOfResource:fixtureName withExtension:nil]; } -+ (NSString *)MIMETypeForFixture:(NSString *)fixtureName { ++ (NSString *)MIMETypeForFixture:(NSString *)fixtureName +{ return [[self fixtureBundle] MIMETypeForResource:fixtureName withExtension:nil]; } -+ (id)parsedObjectWithContentsOfFixture:(NSString *)fixtureName { ++ (id)parsedObjectWithContentsOfFixture:(NSString *)fixtureName +{ return [[self fixtureBundle] parsedObjectWithContentsOfResource:fixtureName withExtension:nil]; } diff --git a/Code/Testing/RKTestNotificationObserver.h b/Code/Testing/RKTestNotificationObserver.h index 12389edd38..9cfa95ad07 100644 --- a/Code/Testing/RKTestNotificationObserver.h +++ b/Code/Testing/RKTestNotificationObserver.h @@ -19,7 +19,7 @@ /** The name of the notification the receiver is awaiting. */ -@property (nonatomic, copy) NSString* name; +@property (nonatomic, copy) NSString *name; /** The object expected to post the notification the receiver is awaiting. diff --git a/Code/Testing/RKTestNotificationObserver.m b/Code/Testing/RKTestNotificationObserver.m index ba20a39ebb..bc248b1a78 100644 --- a/Code/Testing/RKTestNotificationObserver.m +++ b/Code/Testing/RKTestNotificationObserver.m @@ -19,32 +19,38 @@ @implementation RKTestNotificationObserver @synthesize timeout; @synthesize awaitingNotification; -+ (void)waitForNotificationWithName:(NSString *)name object:(id)object usingBlock:(void(^)())block { ++ (void)waitForNotificationWithName:(NSString *)name object:(id)object usingBlock:(void(^)())block +{ RKTestNotificationObserver *observer = [RKTestNotificationObserver notificationObserverForName:name object:object]; block(); [observer waitForNotification]; } -+ (void)waitForNotificationWithName:(NSString *)name usingBlock:(void(^)())block { ++ (void)waitForNotificationWithName:(NSString *)name usingBlock:(void(^)())block +{ [self waitForNotificationWithName:name object:nil usingBlock:block]; } -+ (RKTestNotificationObserver *)notificationObserver { ++ (RKTestNotificationObserver *)notificationObserver +{ return [[[self alloc] init] autorelease]; } -+ (RKTestNotificationObserver *)notificationObserverForName:(NSString *)notificationName object:(id)object { ++ (RKTestNotificationObserver *)notificationObserverForName:(NSString *)notificationName object:(id)object +{ RKTestNotificationObserver *notificationObserver = [self notificationObserver]; notificationObserver.object = object; notificationObserver.name = notificationName; return notificationObserver; } -+ (RKTestNotificationObserver *)notificationObserverForName:(NSString *)notificationName { ++ (RKTestNotificationObserver *)notificationObserverForName:(NSString *)notificationName +{ return [self notificationObserverForName:notificationName object:nil]; } -- (id)init { +- (id)init +{ self = [super init]; if (self) { timeout = 5; @@ -53,12 +59,14 @@ - (id)init { return self; } -- (void)dealloc { +- (void)dealloc +{ [[NSNotificationCenter defaultCenter] removeObserver:self]; [super dealloc]; } -- (void)waitForNotification { +- (void)waitForNotification +{ NSAssert(name, @"Notification name cannot be nil"); [[NSNotificationCenter defaultCenter] addObserver:self @@ -78,7 +86,8 @@ - (void)waitForNotification { } } -- (void)processNotification:(NSNotification*)notification { +- (void)processNotification:(NSNotification *)notification +{ NSAssert([name isEqualToString:notification.name], @"Received notification (%@) differs from expected notification (%@)", notification.name, name); diff --git a/Code/Testing/RKTestResponseLoader.m b/Code/Testing/RKTestResponseLoader.m index a3e47cda41..edb6a6657e 100644 --- a/Code/Testing/RKTestResponseLoader.m +++ b/Code/Testing/RKTestResponseLoader.m @@ -47,11 +47,13 @@ @implementation RKTestResponseLoader @synthesize unexpectedResponse; @synthesize awaitingResponse; -+ (RKTestResponseLoader *)responseLoader { ++ (RKTestResponseLoader *)responseLoader +{ return [[[self alloc] init] autorelease]; } -- (id)init { +- (id)init +{ self = [super init]; if (self) { timeout = 4; @@ -61,7 +63,8 @@ - (id)init { return self; } -- (void)dealloc { +- (void)dealloc +{ [response release]; response = nil; [error release]; @@ -72,7 +75,8 @@ - (void)dealloc { [super dealloc]; } -- (void)waitForResponse { +- (void)waitForResponse +{ awaitingResponse = YES; NSDate *startDate = [NSDate date]; @@ -86,13 +90,15 @@ - (void)waitForResponse { } } -- (void)loadError:(NSError *)theError { +- (void)loadError:(NSError *)theError +{ awaitingResponse = NO; successful = NO; self.error = theError; } -- (NSString *)errorMessage { +- (NSString *)errorMessage +{ if (self.error) { return [[self.error userInfo] valueForKey:NSLocalizedDescriptionKey]; } @@ -100,11 +106,13 @@ - (NSString *)errorMessage { return nil; } -- (void)request:(RKRequest *)request didReceiveResponse:(RKResponse *)response { +- (void)request:(RKRequest *)request didReceiveResponse:(RKResponse *)response +{ // Implemented for expectations } -- (void)request:(RKRequest *)request didLoadResponse:(RKResponse *)aResponse { +- (void)request:(RKRequest *)request didLoadResponse:(RKResponse *)aResponse +{ self.response = aResponse; // If request is an Object Loader, then objectLoader:didLoadObjects: @@ -115,7 +123,8 @@ - (void)request:(RKRequest *)request didLoadResponse:(RKResponse *)aResponse { } } -- (void)request:(RKRequest *)request didFailLoadWithError:(NSError *)anError { +- (void)request:(RKRequest *)request didFailLoadWithError:(NSError *)anError +{ // If request is an Object Loader, then objectLoader:didFailWithError: // will be sent after didFailLoadWithError: if (NO == [request isKindOfClass:[RKObjectLoader class]]) { @@ -126,13 +135,15 @@ - (void)request:(RKRequest *)request didFailLoadWithError:(NSError *)anError { [request cancel]; } -- (void)requestDidCancelLoad:(RKRequest *)request { +- (void)requestDidCancelLoad:(RKRequest *)request +{ awaitingResponse = NO; successful = NO; cancelled = YES; } -- (void)objectLoader:(RKObjectLoader *)objectLoader didLoadObjects:(NSArray *)theObjects { +- (void)objectLoader:(RKObjectLoader *)objectLoader didLoadObjects:(NSArray *)theObjects +{ RKLogTrace(@"%@ Loaded response for %@ with body: %@", self, objectLoader, [objectLoader.response bodyAsString]); RKLogDebug(@"%@ Loaded objects for %@: %@", self, objectLoader, objects); self.objects = theObjects; @@ -140,30 +151,35 @@ - (void)objectLoader:(RKObjectLoader *)objectLoader didLoadObjects:(NSArray *)th successful = YES; } -- (void)objectLoader:(RKObjectLoader *)objectLoader didFailWithError:(NSError *)theError { +- (void)objectLoader:(RKObjectLoader *)objectLoader didFailWithError:(NSError *)theError +{ [self loadError:theError]; } -- (void)objectLoaderDidLoadUnexpectedResponse:(RKObjectLoader *)objectLoader { +- (void)objectLoaderDidLoadUnexpectedResponse:(RKObjectLoader *)objectLoader +{ RKLogDebug(@"%@ Loaded unexpected response for: %@", self, objectLoader); successful = NO; awaitingResponse = NO; unexpectedResponse = YES; } -- (void)objectLoaderDidFinishLoading:(RKObjectLoader *)objectLoader { +- (void)objectLoaderDidFinishLoading:(RKObjectLoader *)objectLoader +{ // Implemented for expectations } #pragma mark - OAuth delegates -- (void)OAuthClient:(RKOAuthClient *)client didAcquireAccessToken:(NSString *)token { +- (void)OAuthClient:(RKOAuthClient *)client didAcquireAccessToken:(NSString *)token +{ awaitingResponse = NO; successful = YES; } -- (void)OAuthClient:(RKOAuthClient *)client didFailWithInvalidGrantError:(NSError *)error { +- (void)OAuthClient:(RKOAuthClient *)client didFailWithInvalidGrantError:(NSError *)error +{ awaitingResponse = NO; successful = NO; } diff --git a/Code/UI/RKAbstractTableController.h b/Code/UI/RKAbstractTableController.h index d6faea9f57..4ceb4b936d 100755 --- a/Code/UI/RKAbstractTableController.h +++ b/Code/UI/RKAbstractTableController.h @@ -36,27 +36,27 @@ */ extern NSString * const RKTableControllerDidStartLoadNotification; -/** +/** Posted when the table controller finishes loading. */ extern NSString * const RKTableControllerDidFinishLoadNotification; -/** +/** Posted when the table controller has loaded objects into the table view. */ extern NSString * const RKTableControllerDidLoadObjectsNotification; -/** +/** Posted when the table controller has loaded an empty collection of objects into the table view. */ extern NSString * const RKTableControllerDidLoadEmptyNotification; -/** +/** Posted when the table controller has loaded an error. */ extern NSString * const RKTableControllerDidLoadErrorNotification; -/** +/** Posted when the table controller has transitioned from an offline to online state. */ extern NSString * const RKTableControllerDidBecomeOnline; @@ -70,41 +70,41 @@ extern NSString * const RKTableControllerDidBecomeOffline; /** @enum RKTableControllerState - + @constant RKTableControllerStateNormal Indicates that the table has loaded normally and is displaying cell content. It is not loading content, is not empty, has not loaded an error, and is not offline. - + @constant RKTableControllerStateLoading Indicates that the table controller is loading content from a remote source. - + @constant RKTableControllerStateEmpty Indicates that the table controller has retrieved an empty collection of objects. - + @constant RKTableControllerStateError Indicates that the table controller has encountered an error while attempting to load. - + @constant RKTableControllerStateOffline Indicates that the table controller is offline and cannot perform network access. - + @constant RKTableControllerStateNotYetLoaded Indicates that the table controller is has not yet attempted a load and state is unknown. */ -enum RKTableControllerState { +enum RKTableControllerState { RKTableControllerStateNormal = 0, RKTableControllerStateLoading = 1 << 1, RKTableControllerStateEmpty = 1 << 2, RKTableControllerStateError = 1 << 3, - RKTableControllerStateOffline = 1 << 4, + RKTableControllerStateOffline = 1 << 4, RKTableControllerStateNotYetLoaded = 0xFF000000 }; typedef NSUInteger RKTableControllerState; /** RKAbstractTableController is an abstract base class for concrete table controller classes. - A table controller object acts as both the delegate and data source for a UITableView + A table controller object acts as both the delegate and data source for a UITableView object and leverages the RestKit object mapping engine to transform local domain models - into UITableViewCell representations. Concrete implementations are provided for the + into UITableViewCell representations. Concrete implementations are provided for the display of static table views and Core Data backed fetched results controller basied table views. */ @@ -212,21 +212,21 @@ typedef NSUInteger RKTableControllerState; /** Returns a Boolean value indicating if the table controller has attempted - a load and transitioned into any state. + a load and transitioned into any state. */ - (BOOL)isLoaded; /** Returns a Boolean value indicating if the table controller has loaded an empty set of content. - + When YES and there is not an empty item configured, the table controller will optionally display an empty image overlayed on top of the table view. - + **NOTE**: It is possible for an empty table controller to display cells witin the managed table view in the event an empty item or header/footer rows are configured. - + @see imageForEmpty */ - (BOOL)isEmpty; @@ -239,10 +239,10 @@ typedef NSUInteger RKTableControllerState; /** Returns a Boolean value indicating if the table controller is offline. - + When YES, the table controller will optionally display an offline image overlayed on top of the table view. - + @see imageForOffline */ - (BOOL)isOffline; @@ -250,10 +250,10 @@ typedef NSUInteger RKTableControllerState; /** Returns a Boolean value indicating if the table controller encountered an error while attempting to load. - + When YES, the table controller will optionally display an error image overlayed on top of the table view. - + @see imageForError */ - (BOOL)isError; @@ -294,12 +294,12 @@ typedef NSUInteger RKTableControllerState; /** Returns the image, if any, configured for display when the table controller - is in the given state. - + is in the given state. + **NOTE** This method accepts a single state value. - + @param state The table controller state - @return The image for the specified state, else nil. Always returns nil for + @return The image for the specified state, else nil. Always returns nil for RKTableControllerStateNormal, RKTableControllerStateLoading and RKTableControllerStateLoading. */ - (UIImage *)imageForState:(RKTableControllerState)state; @@ -339,7 +339,7 @@ typedef NSUInteger RKTableControllerState; /// @name Managing Sections ///----------------------------------------------------------------------------- -/** +/** The number of sections in the table. */ @property (nonatomic, readonly) NSUInteger sectionCount; @@ -362,7 +362,7 @@ typedef NSUInteger RKTableControllerState; /** Returns the UITableViewCell created by applying the specified mapping operation to the object identified by indexPath. - + @param indexPath The indexPath in the tableView for which a cell is needed. */ - (UITableViewCell *)cellForObjectAtIndexPath:(NSIndexPath *)indexPath; @@ -402,7 +402,7 @@ typedef NSUInteger RKTableControllerState; - (void)tableControllerDidCancelLoad:(RKAbstractTableController *)tableController; /** - Sent to the delegate when the controller is really and truly finished loading/updating, whether from the network or from Core Data, + Sent to the delegate when the controller is really and truly finished loading/updating, whether from the network or from Core Data, or from static data, ... this happens in didFinishLoading */ - (void)tableControllerDidFinalizeLoad:(RKAbstractTableController *)tableController; diff --git a/Code/UI/RKAbstractTableController.m b/Code/UI/RKAbstractTableController.m index 9351bbfc64..94f9779397 100755 --- a/Code/UI/RKAbstractTableController.m +++ b/Code/UI/RKAbstractTableController.m @@ -46,7 +46,7 @@ NSString * const RKTableControllerDidBecomeOnline = @"RKTableControllerDidBecomeOnline"; NSString * const RKTableControllerDidBecomeOffline = @"RKTableControllerDidBecomeOffline"; -static NSString * lastUpdatedDateDictionaryKey = @"lastUpdatedDateDictionaryKey"; +static NSString *lastUpdatedDateDictionaryKey = @"lastUpdatedDateDictionaryKey"; @implementation RKAbstractTableController @@ -97,16 +97,19 @@ @implementation RKAbstractTableController #pragma mark - Instantiation + (id)tableControllerWithTableView:(UITableView *)tableView - forViewController:(UIViewController *)viewController { + forViewController:(UIViewController *)viewController +{ return [[[self alloc] initWithTableView:tableView viewController:viewController] autorelease]; } -+ (id)tableControllerForTableViewController:(UITableViewController *)tableViewController { ++ (id)tableControllerForTableViewController:(UITableViewController *)tableViewController +{ return [self tableControllerWithTableView:tableViewController.tableView forViewController:tableViewController]; } -- (id)initWithTableView:(UITableView *)theTableView viewController:(UIViewController *)theViewController { +- (id)initWithTableView:(UITableView *)theTableView viewController:(UIViewController *)theViewController +{ NSAssert(theTableView, @"Cannot initialize a table view model with a nil tableView"); NSAssert(theViewController, @"Cannot initialize a table view model with a nil viewController"); self = [self init]; @@ -122,7 +125,8 @@ - (id)initWithTableView:(UITableView *)theTableView viewController:(UIViewContro return self; } -- (id)init { +- (id)init +{ self = [super init]; if (self) { if ([self isMemberOfClass:[RKAbstractTableController class]]) { @@ -158,7 +162,8 @@ - (id)init { return self; } -- (void)dealloc { +- (void)dealloc +{ // Disconnect from the tableView if (_tableView.delegate == self) _tableView.delegate = nil; if (_tableView.dataSource == self) _tableView.dataSource = nil; @@ -182,7 +187,7 @@ - (void)dealloc { _objectLoader.delegate = nil; [_objectLoader release]; _objectLoader = nil; - + [_cellMappings release]; [_headerItems release]; [_footerItems release]; @@ -193,20 +198,23 @@ - (void)dealloc { [super dealloc]; } -- (void)setTableView:(UITableView *)tableView { +- (void)setTableView:(UITableView *)tableView +{ NSAssert(tableView, @"Cannot assign a nil tableView to the model"); _tableView = tableView; _tableView.delegate = self; _tableView.dataSource = self; } -- (void)setViewController:(UIViewController *)viewController { +- (void)setViewController:(UIViewController *)viewController +{ if ([viewController isKindOfClass:[UITableViewController class]]) { - self.tableView = [(UITableViewController*)viewController tableView]; + self.tableView = [(UITableViewController *)viewController tableView]; } } -- (void)setObjectManager:(RKObjectManager *)objectManager { +- (void)setObjectManager:(RKObjectManager *)objectManager +{ NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; // Remove observers @@ -243,7 +251,8 @@ - (void)setObjectManager:(RKObjectManager *)objectManager { } } -- (void)setAutoResizesForKeyboard:(BOOL)autoResizesForKeyboard { +- (void)setAutoResizesForKeyboard:(BOOL)autoResizesForKeyboard +{ if (_autoResizesForKeyboard != autoResizesForKeyboard) { _autoResizesForKeyboard = autoResizesForKeyboard; if (_autoResizesForKeyboard) { @@ -262,7 +271,8 @@ - (void)setAutoResizesForKeyboard:(BOOL)autoResizesForKeyboard { } } -- (void)setAutoRefreshFromNetwork:(BOOL)autoRefreshFromNetwork { +- (void)setAutoRefreshFromNetwork:(BOOL)autoRefreshFromNetwork +{ if (_autoRefreshFromNetwork != autoRefreshFromNetwork) { _autoRefreshFromNetwork = autoRefreshFromNetwork; if (_autoRefreshFromNetwork) { @@ -279,92 +289,105 @@ - (void)setAutoRefreshFromNetwork:(BOOL)autoRefreshFromNetwork { } } -- (void)setLoading:(BOOL)loading { +- (void)setLoading:(BOOL)loading +{ if (loading) { self.state |= RKTableControllerStateLoading; } else { - self.state &= ~RKTableControllerStateLoading; + self.state &= ~RKTableControllerStateLoading; } } // NOTE: The loaded flag is handled specially. When loaded becomes NO, // we clear all other flags. In practice this should not happen outside of init. -- (void)setLoaded:(BOOL)loaded { +- (void)setLoaded:(BOOL)loaded +{ if (loaded) { self.state &= ~RKTableControllerStateNotYetLoaded; } else { - self.state = RKTableControllerStateNotYetLoaded; + self.state = RKTableControllerStateNotYetLoaded; } } -- (void)setEmpty:(BOOL)empty { +- (void)setEmpty:(BOOL)empty +{ if (empty) { self.state |= RKTableControllerStateEmpty; } else { - self.state &= ~RKTableControllerStateEmpty; + self.state &= ~RKTableControllerStateEmpty; } } -- (void)setOffline:(BOOL)offline { +- (void)setOffline:(BOOL)offline +{ if (offline) { self.state |= RKTableControllerStateOffline; } else { - self.state &= ~RKTableControllerStateOffline; + self.state &= ~RKTableControllerStateOffline; } } -- (void)setErrorState:(BOOL)error { +- (void)setErrorState:(BOOL)error +{ if (error) { self.state |= RKTableControllerStateError; } else { - self.state &= ~RKTableControllerStateError; + self.state &= ~RKTableControllerStateError; } } -- (void)objectManagerConnectivityDidChange:(NSNotification *)notification { +- (void)objectManagerConnectivityDidChange:(NSNotification *)notification +{ RKLogTrace(@"%@ received network status change notification: %@", self, [notification name]); [self setOffline:!self.objectManager.isOnline]; } #pragma mark - Abstract Methods -- (BOOL)isConsideredEmpty { +- (BOOL)isConsideredEmpty +{ @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"You must override %@ in a subclass", NSStringFromSelector(_cmd)] userInfo:nil]; } -- (NSUInteger)sectionCount { +- (NSUInteger)sectionCount +{ @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"You must override %@ in a subclass", NSStringFromSelector(_cmd)] userInfo:nil]; } -- (NSUInteger)rowCount { +- (NSUInteger)rowCount +{ @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"You must override %@ in a subclass", NSStringFromSelector(_cmd)] userInfo:nil]; } -- (id)objectForRowAtIndexPath:(NSIndexPath *)indexPath { +- (id)objectForRowAtIndexPath:(NSIndexPath *)indexPath +{ @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"You must override %@ in a subclass", NSStringFromSelector(_cmd)] userInfo:nil]; } -- (NSIndexPath *)indexPathForObject:(id)object { +- (NSIndexPath *)indexPathForObject:(id)object +{ @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"You must override %@ in a subclass", NSStringFromSelector(_cmd)] userInfo:nil]; } -- (NSUInteger)numberOfRowsInSection:(NSUInteger)index { +- (NSUInteger)numberOfRowsInSection:(NSUInteger)index +{ @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"You must override %@ in a subclass", NSStringFromSelector(_cmd)] userInfo:nil]; } -- (UITableViewCell *)cellForObjectAtIndexPath:(NSIndexPath *)indexPath { +- (UITableViewCell *)cellForObjectAtIndexPath:(NSIndexPath *)indexPath +{ @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"You must override %@ in a subclass", NSStringFromSelector(_cmd)] userInfo:nil]; @@ -372,75 +395,88 @@ - (UITableViewCell *)cellForObjectAtIndexPath:(NSIndexPath *)indexPath { #pragma mark - Cell Mappings -- (void)mapObjectsWithClass:(Class)objectClass toTableCellsWithMapping:(RKTableViewCellMapping *)cellMapping { +- (void)mapObjectsWithClass:(Class)objectClass toTableCellsWithMapping:(RKTableViewCellMapping *)cellMapping +{ // TODO: Should we raise an exception/throw a warning if you are doing class mapping for a type // that implements a cellMapping instance method? Maybe a class declaration overrides [_cellMappings setCellMapping:cellMapping forClass:objectClass]; } -- (void)mapObjectsWithClassName:(NSString *)objectClassName toTableCellsWithMapping:(RKTableViewCellMapping *)cellMapping { +- (void)mapObjectsWithClassName:(NSString *)objectClassName toTableCellsWithMapping:(RKTableViewCellMapping *)cellMapping +{ [self mapObjectsWithClass:NSClassFromString(objectClassName) toTableCellsWithMapping:cellMapping]; } -- (RKTableViewCellMapping *)cellMappingForObjectAtIndexPath:(NSIndexPath *)indexPath { +- (RKTableViewCellMapping *)cellMappingForObjectAtIndexPath:(NSIndexPath *)indexPath +{ NSAssert(indexPath, @"Cannot lookup cell mapping for object with a nil indexPath"); id object = [self objectForRowAtIndexPath:indexPath]; return [self.cellMappings cellMappingForObject:object]; } -- (UITableViewCell *)cellForObject:(id)object { +- (UITableViewCell *)cellForObject:(id)object +{ NSIndexPath *indexPath = [self indexPathForObject:object]; return indexPath ? [self cellForObjectAtIndexPath:indexPath] : nil; } #pragma mark - Header and Footer Rows -- (void)addHeaderRowForItem:(RKTableItem *)tableItem { +- (void)addHeaderRowForItem:(RKTableItem *)tableItem +{ [_headerItems addObject:tableItem]; } -- (void)addFooterRowForItem:(RKTableItem *)tableItem { +- (void)addFooterRowForItem:(RKTableItem *)tableItem +{ [_footerItems addObject:tableItem]; } -- (void)addHeaderRowWithMapping:(RKTableViewCellMapping *)cellMapping { +- (void)addHeaderRowWithMapping:(RKTableViewCellMapping *)cellMapping +{ RKTableItem *tableItem = [RKTableItem tableItem]; tableItem.cellMapping = cellMapping; [self addHeaderRowForItem:tableItem]; } -- (void)addFooterRowWithMapping:(RKTableViewCellMapping *)cellMapping { +- (void)addFooterRowWithMapping:(RKTableViewCellMapping *)cellMapping +{ RKTableItem *tableItem = [RKTableItem tableItem]; tableItem.cellMapping = cellMapping; [self addFooterRowForItem:tableItem]; } -- (void)removeAllHeaderRows { +- (void)removeAllHeaderRows +{ [_headerItems removeAllObjects]; } -- (void)removeAllFooterRows { +- (void)removeAllFooterRows +{ [_footerItems removeAllObjects]; } #pragma mark - UITableViewDataSource methods -- (UITableViewCell *)tableView:(UITableView *)theTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { +- (UITableViewCell *)tableView:(UITableView *)theTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath +{ NSAssert(theTableView == self.tableView, @"tableView:cellForRowAtIndexPath: invoked with inappropriate tableView: %@", theTableView); UITableViewCell *cell = [self cellForObjectAtIndexPath:indexPath]; - + RKLogTrace(@"%@ cellForRowAtIndexPath:%@ = %@", self, indexPath, cell); return cell; } -- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { +- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section +{ [NSException raise:@"Must be implemented in a subclass!" format:@"sectionCount must be implemented with a subclass"]; return 0; } #pragma mark - UITableViewDelegate methods -- (void)tableView:(UITableView *)theTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { +- (void)tableView:(UITableView *)theTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath +{ NSAssert(theTableView == self.tableView, @"tableView:didSelectRowAtIndexPath: invoked with inappropriate tableView: %@", theTableView); RKLogTrace(@"%@: Row at indexPath %@ selected for tableView %@", self, indexPath, theTableView); @@ -464,13 +500,14 @@ - (void)tableView:(UITableView *)theTableView didSelectRowAtIndexPath:(NSIndexPa RKLogTrace(@"%@: Invoking onSelectCellForObjectAtIndexPath block with cellMapping %@ for object %@ at indexPath = %@", self, cell, object, indexPath); cellMapping.onSelectCellForObjectAtIndexPath(cell, object, indexPath); } - + if ([self.delegate respondsToSelector:@selector(tableController:didSelectCell:forObject:atIndexPath:)]) { [self.delegate tableController:self didSelectCell:cell forObject:object atIndexPath:indexPath]; } } -- (void)tableView:(UITableView *)theTableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath { +- (void)tableView:(UITableView *)theTableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath +{ NSAssert(theTableView == self.tableView, @"tableView:didSelectRowAtIndexPath: invoked with inappropriate tableView: %@", theTableView); cell.hidden = NO; id mappableObject = [self objectForRowAtIndexPath:indexPath]; @@ -478,7 +515,7 @@ - (void)tableView:(UITableView *)theTableView willDisplayCell:(UITableViewCell * if (cellMapping.onCellWillAppearForObjectAtIndexPath) { cellMapping.onCellWillAppearForObjectAtIndexPath(cell, mappableObject, indexPath); } - + if ([self.delegate respondsToSelector:@selector(tableController:willDisplayCell:forObject:atIndexPath:)]) { [self.delegate tableController:self willDisplayCell:cell forObject:mappableObject atIndexPath:indexPath]; } @@ -508,7 +545,8 @@ - (void)tableView:(UITableView *)theTableView willDisplayCell:(UITableViewCell * // Variable height support -- (CGFloat)tableView:(UITableView *)theTableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { +- (CGFloat)tableView:(UITableView *)theTableView heightForRowAtIndexPath:(NSIndexPath *)indexPath +{ if (self.variableHeightRows) { RKTableViewCellMapping *cellMapping = [self cellMappingForObjectAtIndexPath:indexPath]; @@ -527,7 +565,8 @@ - (CGFloat)tableView:(UITableView *)theTableView heightForRowAtIndexPath:(NSInde return self.tableView.rowHeight; } -- (void)tableView:(UITableView *)theTableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath { +- (void)tableView:(UITableView *)theTableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath +{ RKTableViewCellMapping *cellMapping = [self cellMappingForObjectAtIndexPath:indexPath]; if (cellMapping.onTapAccessoryButtonForObjectAtIndexPath) { RKLogTrace(@"Found a block for tableView:accessoryButtonTappedForRowWithIndexPath: Executing..."); @@ -537,7 +576,8 @@ - (void)tableView:(UITableView *)theTableView accessoryButtonTappedForRowWithInd } } -- (NSString *)tableView:(UITableView *)theTableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath { +- (NSString *)tableView:(UITableView *)theTableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath +{ RKTableViewCellMapping *cellMapping = [self cellMappingForObjectAtIndexPath:indexPath]; if (cellMapping.titleForDeleteButtonForObjectAtIndexPath) { RKLogTrace(@"Found a block for tableView:titleForDeleteConfirmationButtonForRowAtIndexPath: Executing..."); @@ -548,7 +588,8 @@ - (NSString *)tableView:(UITableView *)theTableView titleForDeleteConfirmationBu return NSLocalizedString(@"Delete", nil); } -- (UITableViewCellEditingStyle)tableView:(UITableView *)theTableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath { +- (UITableViewCellEditingStyle)tableView:(UITableView *)theTableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath +{ if (_canEditRows) { RKTableViewCellMapping *cellMapping = [self cellMappingForObjectAtIndexPath:indexPath]; UITableViewCell *cell = [self tableView:self.tableView cellForRowAtIndexPath:indexPath]; @@ -562,21 +603,24 @@ - (UITableViewCellEditingStyle)tableView:(UITableView *)theTableView editingStyl return UITableViewCellEditingStyleNone; } -- (void)tableView:(UITableView *)theTableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath { +- (void)tableView:(UITableView *)theTableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath +{ if ([self.delegate respondsToSelector:@selector(tableController:didEndEditing:atIndexPath:)]) { id object = [self objectForRowAtIndexPath:indexPath]; [self.delegate tableController:self didEndEditing:object atIndexPath:indexPath]; } } -- (void)tableView:(UITableView *)theTableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath { +- (void)tableView:(UITableView *)theTableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath +{ if ([self.delegate respondsToSelector:@selector(tableController:willBeginEditing:atIndexPath:)]) { id object = [self objectForRowAtIndexPath:indexPath]; [self.delegate tableController:self willBeginEditing:object atIndexPath:indexPath]; } } -- (NSIndexPath *)tableView:(UITableView *)theTableView targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath { +- (NSIndexPath *)tableView:(UITableView *)theTableView targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath +{ if (_canMoveRows) { RKTableViewCellMapping *cellMapping = [self cellMappingForObjectAtIndexPath:sourceIndexPath]; if (cellMapping.targetIndexPathForMove) { @@ -589,18 +633,21 @@ - (NSIndexPath *)tableView:(UITableView *)theTableView targetIndexPathForMoveFro return proposedDestinationIndexPath; } -- (NSIndexPath *)tableView:(UITableView *)theTableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath { +- (NSIndexPath *)tableView:(UITableView *)theTableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath +{ [self removeSwipeView:YES]; return indexPath; } #pragma mark - Network Table Loading -- (void)cancelLoad { +- (void)cancelLoad +{ [self.objectLoader cancel]; } -- (NSDate *)lastUpdatedDate { +- (NSDate *)lastUpdatedDate +{ if (! self.objectLoader) { return nil; } @@ -620,7 +667,8 @@ - (NSDate *)lastUpdatedDate { return nil; } -- (BOOL)isAutoRefreshNeeded { +- (BOOL)isAutoRefreshNeeded +{ BOOL isAutoRefreshNeeded = NO; if (_autoRefreshFromNetwork) { isAutoRefreshNeeded = YES; @@ -637,12 +685,14 @@ - (BOOL)isAutoRefreshNeeded { #pragma mark - RKRequestDelegate & RKObjectLoaderDelegate methods -- (void)requestDidStartLoad:(RKRequest *)request { +- (void)requestDidStartLoad:(RKRequest *)request +{ RKLogTrace(@"tableController %@ started loading.", self); [self didStartLoad]; } -- (void)requestDidCancelLoad:(RKRequest *)request { +- (void)requestDidCancelLoad:(RKRequest *)request +{ RKLogTrace(@"tableController %@ cancelled loading.", self); self.loading = NO; @@ -651,12 +701,14 @@ - (void)requestDidCancelLoad:(RKRequest *)request { } } -- (void)requestDidTimeout:(RKRequest *)request { +- (void)requestDidTimeout:(RKRequest *)request +{ RKLogTrace(@"tableController %@ timed out while loading.", self); self.loading = NO; } -- (void)request:(RKRequest *)request didLoadResponse:(RKResponse *)response { +- (void)request:(RKRequest *)request didLoadResponse:(RKResponse *)response +{ RKLogTrace(@"tableController %@ finished loading.", self); // Updated the lastUpdatedDate dictionary using the URL of the request @@ -677,12 +729,14 @@ - (void)request:(RKRequest *)request didLoadResponse:(RKResponse *)response { } } -- (void)objectLoader:(RKObjectLoader *)objectLoader didFailWithError:(NSError *)error { +- (void)objectLoader:(RKObjectLoader *)objectLoader didFailWithError:(NSError *)error +{ RKLogError(@"tableController %@ failed network load with error: %@", self, error); [self didFailLoadWithError:error]; } -- (void)objectLoaderDidFinishLoading:(RKObjectLoader *)objectLoader { +- (void)objectLoaderDidFinishLoading:(RKObjectLoader *)objectLoader +{ if ([self.delegate respondsToSelector:@selector(tableController:didLoadTableWithObjectLoader:)]) { [self.delegate tableController:self didLoadTableWithObjectLoader:objectLoader]; } @@ -691,63 +745,69 @@ - (void)objectLoaderDidFinishLoading:(RKObjectLoader *)objectLoader { [self didFinishLoad]; } -- (void)didStartLoad { +- (void)didStartLoad +{ self.loading = YES; } -- (void)didFailLoadWithError:(NSError *)error { +- (void)didFailLoadWithError:(NSError *)error +{ self.error = error; [self didFinishLoad]; } -- (void)didFinishLoad { +- (void)didFinishLoad +{ self.empty = [self isConsideredEmpty]; self.loading = [self.objectLoader isLoading]; // Mutate loading state after we have adjusted empty self.loaded = YES; - + if (![self isEmpty] && ![self isLoading]) { [[NSNotificationCenter defaultCenter] postNotificationName:RKTableControllerDidLoadObjectsNotification object:self]; } - - if (self.delegate && [_delegate respondsToSelector:@selector(tableControllerDidFinalizeLoad:)]) { - [self.delegate performSelector:@selector(tableControllerDidFinalizeLoad:) withObject:self]; + + if (self.delegate && [_delegate respondsToSelector:@selector(tableControllerDidFinalizeLoad:)]) { + [self.delegate performSelector:@selector(tableControllerDidFinalizeLoad:) withObject:self]; } } #pragma mark - Table Overlay Views -- (UIImage *)imageForState:(RKTableControllerState)state { +- (UIImage *)imageForState:(RKTableControllerState)state +{ switch (state) { case RKTableControllerStateNormal: case RKTableControllerStateLoading: case RKTableControllerStateNotYetLoaded: break; - + case RKTableControllerStateEmpty: return self.imageForEmpty; break; - + case RKTableControllerStateError: return self.imageForError; break; - + case RKTableControllerStateOffline: return self.imageForOffline; break; - + default: break; } - + return nil; } -- (UIImage *)overlayImage { +- (UIImage *)overlayImage +{ return _stateOverlayImageView.image; } // Adds an overlay view above the table -- (void)addToOverlayView:(UIView *)view modally:(BOOL)modally { +- (void)addToOverlayView:(UIView *)view modally:(BOOL)modally +{ if (! _tableOverlayView) { CGRect overlayFrame = CGRectIsEmpty(self.overlayFrame) ? self.tableView.frame : self.overlayFrame; _tableOverlayView = [[UIView alloc] initWithFrame:overlayFrame]; @@ -773,7 +833,8 @@ - (void)addToOverlayView:(UIView *)view modally:(BOOL)modally { [_tableOverlayView addSubview:view]; } -- (void)resetOverlayView { +- (void)resetOverlayView +{ if (_stateOverlayImageView && _stateOverlayImageView.image == nil) { [_stateOverlayImageView removeFromSuperview]; } @@ -784,7 +845,8 @@ - (void)resetOverlayView { } } -- (void)addSubviewOverTableView:(UIView *)view { +- (void)addSubviewOverTableView:(UIView *)view +{ NSInteger tableIndex = [_tableView.superview.subviews indexOfObject:_tableView]; if (NSNotFound != tableIndex) { @@ -792,7 +854,8 @@ - (void)addSubviewOverTableView:(UIView *)view { } } -- (BOOL)removeImageFromOverlay:(UIImage *)image { +- (BOOL)removeImageFromOverlay:(UIImage *)image +{ if (image && _stateOverlayImageView.image == image) { _stateOverlayImageView.image = nil; return YES; @@ -800,7 +863,8 @@ - (BOOL)removeImageFromOverlay:(UIImage *)image { return NO; } -- (void)showImageInOverlay:(UIImage *)image { +- (void)showImageInOverlay:(UIImage *)image +{ NSAssert(self.tableView, @"Cannot add an overlay image to a nil tableView"); if (! _stateOverlayImageView) { _stateOverlayImageView = [[UIImageView alloc] initWithFrame:CGRectZero]; @@ -812,13 +876,15 @@ - (void)showImageInOverlay:(UIImage *)image { [self addToOverlayView:_stateOverlayImageView modally:self.showsOverlayImagesModally]; } -- (void)removeImageOverlay { +- (void)removeImageOverlay +{ _stateOverlayImageView.image = nil; [_stateOverlayImageView removeFromSuperview]; [self resetOverlayView]; } -- (void)setImageForEmpty:(UIImage *)imageForEmpty { +- (void)setImageForEmpty:(UIImage *)imageForEmpty +{ [imageForEmpty retain]; BOOL imageRemoved = [self removeImageFromOverlay:_imageForEmpty]; [_imageForEmpty release]; @@ -826,7 +892,8 @@ - (void)setImageForEmpty:(UIImage *)imageForEmpty { if (imageRemoved) [self showImageInOverlay:_imageForEmpty]; } -- (void)setImageForError:(UIImage *)imageForError { +- (void)setImageForError:(UIImage *)imageForError +{ [imageForError retain]; BOOL imageRemoved = [self removeImageFromOverlay:_imageForError]; [_imageForError release]; @@ -834,7 +901,8 @@ - (void)setImageForError:(UIImage *)imageForError { if (imageRemoved) [self showImageInOverlay:_imageForError]; } -- (void)setImageForOffline:(UIImage *)imageForOffline { +- (void)setImageForOffline:(UIImage *)imageForOffline +{ [imageForOffline retain]; BOOL imageRemoved = [self removeImageFromOverlay:_imageForOffline]; [_imageForOffline release]; @@ -842,7 +910,8 @@ - (void)setImageForOffline:(UIImage *)imageForOffline { if (imageRemoved) [self showImageInOverlay:_imageForOffline]; } -- (void)setLoadingView:(UIView *)loadingView { +- (void)setLoadingView:(UIView *)loadingView +{ [loadingView retain]; BOOL viewRemoved = (_loadingView.superview != nil); [_loadingView removeFromSuperview]; @@ -854,31 +923,38 @@ - (void)setLoadingView:(UIView *)loadingView { #pragma mark - KVO & Table States -- (BOOL)isLoading { +- (BOOL)isLoading +{ return (self.state & RKTableControllerStateLoading) != 0; } -- (BOOL)isLoaded { +- (BOOL)isLoaded +{ return (self.state & RKTableControllerStateNotYetLoaded) == 0; // return self.state != RKTableControllerStateNotYetLoaded; } -- (BOOL)isOffline { +- (BOOL)isOffline +{ return (self.state & RKTableControllerStateOffline) != 0; } -- (BOOL)isOnline { +- (BOOL)isOnline +{ return ![self isOffline]; } -- (BOOL)isError { +- (BOOL)isError +{ return (self.state & RKTableControllerStateError) != 0; } -- (BOOL)isEmpty { +- (BOOL)isEmpty +{ return (self.state & RKTableControllerStateEmpty) != 0; } -- (void)isLoadingDidChange { +- (void)isLoadingDidChange +{ if ([self isLoading]) { if ([self.delegate respondsToSelector:@selector(tableControllerDidStartLoad:)]) { [self.delegate tableControllerDidStartLoad:self]; @@ -908,7 +984,8 @@ - (void)isLoadingDidChange { _stateOverlayImageView.hidden = [self isLoading]; } -- (void)isLoadedDidChange { +- (void)isLoadedDidChange +{ if ([self isLoaded]) { RKLogDebug(@"%@: is now loaded.", self); } else { @@ -916,7 +993,8 @@ - (void)isLoadedDidChange { } } -- (void)isErrorDidChange { +- (void)isErrorDidChange +{ if ([self isError]) { if ([self.delegate respondsToSelector:@selector(tableController:didFailLoadWithError:)]) { [self.delegate tableController:self didFailLoadWithError:self.error]; @@ -927,7 +1005,8 @@ - (void)isErrorDidChange { } } -- (void)isEmptyDidChange { +- (void)isEmptyDidChange +{ if ([self isEmpty]) { if ([self.delegate respondsToSelector:@selector(tableControllerDidBecomeEmpty:)]) { [self.delegate tableControllerDidBecomeEmpty:self]; @@ -937,7 +1016,8 @@ - (void)isEmptyDidChange { } } -- (void)isOnlineDidChange { +- (void)isOnlineDidChange +{ if ([self isOnline]) { // We just transitioned to online if ([self.delegate respondsToSelector:@selector(tableControllerDidBecomeOnline:)]) { @@ -952,29 +1032,30 @@ - (void)isOnlineDidChange { } [[NSNotificationCenter defaultCenter] postNotificationName:RKTableControllerDidBecomeOffline object:self]; - } + } } -- (void)updateTableViewForStateChange:(NSDictionary *)change { +- (void)updateTableViewForStateChange:(NSDictionary *)change +{ RKTableControllerState oldState = [[change valueForKey:NSKeyValueChangeOldKey] integerValue]; RKTableControllerState newState = [[change valueForKey:NSKeyValueChangeNewKey] integerValue]; - + // Determine state transitions BOOL loadedChanged = ((oldState ^ newState) & RKTableControllerStateNotYetLoaded); BOOL emptyChanged = ((oldState ^ newState) & RKTableControllerStateEmpty); BOOL offlineChanged = ((oldState ^ newState) & RKTableControllerStateOffline); BOOL loadingChanged = ((oldState ^ newState) & RKTableControllerStateLoading); BOOL errorChanged = ((oldState ^ newState) & RKTableControllerStateError); - + if (loadedChanged) [self isLoadedDidChange]; if (emptyChanged) [self isEmptyDidChange]; if (offlineChanged) [self isOnlineDidChange]; if (errorChanged) [self isErrorDidChange]; if (loadingChanged) [self isLoadingDidChange]; - + // Clear the image from the overlay _stateOverlayImageView.image = nil; - + // Determine the appropriate overlay image to display (if any) if (self.state == RKTableControllerStateNormal) { [self removeImageOverlay]; @@ -983,7 +1064,7 @@ - (void)updateTableViewForStateChange:(NSDictionary *)change { // During a load we don't adjust the overlay return; } - + // Though the table can be in more than one state, we only // want to display a single overlay image. if ([self isOffline] && self.imageForOffline) { @@ -994,12 +1075,13 @@ - (void)updateTableViewForStateChange:(NSDictionary *)change { [self showImageInOverlay:self.imageForEmpty]; } } - + // Remove the overlay if no longer in use [self resetOverlayView]; } -- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { +- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context +{ if ([keyPath isEqualToString:@"state"]) { [self updateTableViewForStateChange:change]; } else if ([keyPath isEqualToString:@"error"]) { @@ -1009,7 +1091,8 @@ - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(N #pragma mark - Pull to Refresh -- (RKRefreshGestureRecognizer *)pullToRefreshGestureRecognizer { +- (RKRefreshGestureRecognizer *)pullToRefreshGestureRecognizer +{ RKRefreshGestureRecognizer *refreshRecognizer = nil; for (RKRefreshGestureRecognizer *recognizer in self.tableView.gestureRecognizers) { if ([recognizer isKindOfClass:[RKRefreshGestureRecognizer class]]) { @@ -1020,7 +1103,8 @@ - (RKRefreshGestureRecognizer *)pullToRefreshGestureRecognizer { return refreshRecognizer; } -- (void)setPullToRefreshEnabled:(BOOL)pullToRefreshEnabled { +- (void)setPullToRefreshEnabled:(BOOL)pullToRefreshEnabled +{ RKRefreshGestureRecognizer *recognizer = nil; if (pullToRefreshEnabled) { recognizer = [[[RKRefreshGestureRecognizer alloc] initWithTarget:self action:@selector(pullToRefreshStateChanged:)] autorelease]; @@ -1034,7 +1118,8 @@ - (void)setPullToRefreshEnabled:(BOOL)pullToRefreshEnabled { _pullToRefreshEnabled = pullToRefreshEnabled; } -- (void)pullToRefreshStateChanged:(UIGestureRecognizer *)gesture { +- (void)pullToRefreshStateChanged:(UIGestureRecognizer *)gesture +{ if (gesture.state == UIGestureRecognizerStateRecognized) { if ([self pullToRefreshDataSourceIsLoading:gesture]) return; @@ -1046,25 +1131,29 @@ - (void)pullToRefreshStateChanged:(UIGestureRecognizer *)gesture { } } -- (void)resetPullToRefreshRecognizer { +- (void)resetPullToRefreshRecognizer +{ RKRefreshGestureRecognizer *recognizer = [self pullToRefreshGestureRecognizer]; if (recognizer) [recognizer setRefreshState:RKRefreshIdle]; } -- (BOOL)pullToRefreshDataSourceIsLoading:(UIGestureRecognizer *)gesture { +- (BOOL)pullToRefreshDataSourceIsLoading:(UIGestureRecognizer *)gesture +{ // If we have already been loaded and we are loading again, a refresh is taking place... return [self isLoaded] && [self isLoading] && [self isOnline]; } -- (NSDate *)pullToRefreshDataSourceLastUpdated:(UIGestureRecognizer *)gesture { +- (NSDate *)pullToRefreshDataSourceLastUpdated:(UIGestureRecognizer *)gesture +{ NSDate *dataSourceLastUpdated = [self lastUpdatedDate]; return dataSourceLastUpdated ? dataSourceLastUpdated : [NSDate date]; } #pragma mark - Cell Swipe Menu Methods -- (void)setupSwipeGestureRecognizers { +- (void)setupSwipeGestureRecognizers +{ // Setup a right swipe gesture recognizer UISwipeGestureRecognizer *rightSwipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeRight:)]; rightSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirectionRight; @@ -1078,7 +1167,8 @@ - (void)setupSwipeGestureRecognizers { [leftSwipeGestureRecognizer release]; } -- (void)removeSwipeGestureRecognizers { +- (void)removeSwipeGestureRecognizers +{ for (UIGestureRecognizer *recognizer in self.tableView.gestureRecognizers) { if ([recognizer isKindOfClass:[UISwipeGestureRecognizer class]]) { [self.tableView removeGestureRecognizer:recognizer]; @@ -1086,12 +1176,14 @@ - (void)removeSwipeGestureRecognizers { } } -- (void)setCanEditRows:(BOOL)canEditRows { +- (void)setCanEditRows:(BOOL)canEditRows +{ NSAssert(!_cellSwipeViewsEnabled, @"Table model cannot be made editable when cell swipe menus are enabled"); _canEditRows = canEditRows; } -- (void)setCellSwipeViewsEnabled:(BOOL)cellSwipeViewsEnabled { +- (void)setCellSwipeViewsEnabled:(BOOL)cellSwipeViewsEnabled +{ NSAssert(!_canEditRows, @"Cell swipe menus cannot be enabled for editable tableModels"); if (cellSwipeViewsEnabled) { [self setupSwipeGestureRecognizers]; @@ -1102,7 +1194,8 @@ - (void)setCellSwipeViewsEnabled:(BOOL)cellSwipeViewsEnabled { _cellSwipeViewsEnabled = cellSwipeViewsEnabled; } -- (void)swipe:(UISwipeGestureRecognizer *)recognizer direction:(UISwipeGestureRecognizerDirection)direction { +- (void)swipe:(UISwipeGestureRecognizer *)recognizer direction:(UISwipeGestureRecognizerDirection)direction +{ if (_cellSwipeViewsEnabled && recognizer && recognizer.state == UIGestureRecognizerStateEnded) { CGPoint location = [recognizer locationInView:self.tableView]; NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location]; @@ -1122,15 +1215,18 @@ - (void)swipe:(UISwipeGestureRecognizer *)recognizer direction:(UISwipeGestureRe } } -- (void)swipeLeft:(UISwipeGestureRecognizer *)recognizer { +- (void)swipeLeft:(UISwipeGestureRecognizer *)recognizer +{ [self swipe:recognizer direction:UISwipeGestureRecognizerDirectionLeft]; } -- (void)swipeRight:(UISwipeGestureRecognizer *)recognizer { +- (void)swipeRight:(UISwipeGestureRecognizer *)recognizer +{ [self swipe:recognizer direction:UISwipeGestureRecognizerDirectionRight]; } -- (void)addSwipeViewTo:(UITableViewCell *)cell withObject:(id)object direction:(UISwipeGestureRecognizerDirection)direction { +- (void)addSwipeViewTo:(UITableViewCell *)cell withObject:(id)object direction:(UISwipeGestureRecognizerDirection)direction +{ if (_cellSwipeViewsEnabled) { NSAssert(cell, @"Cannot process swipe view with nil cell"); NSAssert(object, @"Cannot process swipe view with nil object"); @@ -1165,11 +1261,13 @@ - (void)addSwipeViewTo:(UITableViewCell *)cell withObject:(id)object direction:( } } -- (void)animationDidStopAddingSwipeView:(NSString *)animationID finished:(NSNumber *)finished context:(void*)context { +- (void)animationDidStopAddingSwipeView:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context +{ _animatingCellSwipe = NO; } -- (void)removeSwipeView:(BOOL)animated { +- (void)removeSwipeView:(BOOL)animated +{ if (!_cellSwipeViewsEnabled || !_swipeCell || _animatingCellSwipe) { RKLogTrace(@"Exiting early with _cellSwipeViewsEnabled=%d, _swipCell=%@, _animatingCellSwipe=%d", _cellSwipeViewsEnabled, _swipeCell, _animatingCellSwipe); @@ -1197,13 +1295,14 @@ - (void)removeSwipeView:(BOOL)animated { [UIView commitAnimations]; } else { [_cellSwipeView removeFromSuperview]; - _swipeCell.frame = CGRectMake(0,_swipeCell.frame.origin.y,_swipeCell.frame.size.width, _swipeCell.frame.size.height); + _swipeCell.frame = CGRectMake(0, _swipeCell.frame.origin.y, _swipeCell.frame.size.width, _swipeCell.frame.size.height); [_swipeCell release]; _swipeCell = nil; } } -- (void)animationDidStopOne:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context { +- (void)animationDidStopOne:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context +{ [UIView beginAnimations:nil context:nil]; [UIView setAnimationDuration:0.2]; if (_swipeDirection == UISwipeGestureRecognizerDirectionRight) { @@ -1217,7 +1316,8 @@ - (void)animationDidStopOne:(NSString *)animationID finished:(NSNumber *)finishe [UIView commitAnimations]; } -- (void)animationDidStopTwo:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context { +- (void)animationDidStopTwo:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context +{ [UIView commitAnimations]; [UIView beginAnimations:nil context:nil]; [UIView setAnimationDuration:0.2]; @@ -1232,7 +1332,8 @@ - (void)animationDidStopTwo:(NSString *)animationID finished:(NSNumber *)finishe [UIView commitAnimations]; } -- (void)animationDidStopThree:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context { +- (void)animationDidStopThree:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context +{ _animatingCellSwipe = NO; [_swipeCell release]; _swipeCell = nil; @@ -1241,18 +1342,21 @@ - (void)animationDidStopThree:(NSString *)animationID finished:(NSNumber *)finis #pragma mark UIScrollViewDelegate methods -- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView { +- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView +{ [self removeSwipeView:YES]; } -- (BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView { +- (BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView +{ [self removeSwipeView:NO]; return YES; } #pragma mark - Keyboard Notification methods -- (void)resizeTableViewForKeyboard:(NSNotification *)notification { +- (void)resizeTableViewForKeyboard:(NSNotification *)notification +{ NSAssert(_autoResizesForKeyboard, @"Errantly receiving keyboard notifications while autoResizesForKeyboard=NO"); NSDictionary *userInfo = [notification userInfo]; @@ -1318,14 +1422,15 @@ - (void)resizeTableViewForKeyboard:(NSNotification *)notification { } } -- (void)loadTableWithObjectLoader:(RKObjectLoader *)theObjectLoader { +- (void)loadTableWithObjectLoader:(RKObjectLoader *)theObjectLoader +{ NSAssert(theObjectLoader, @"Cannot perform a network load without an object loader"); if (! [self.objectLoader isEqual:theObjectLoader]) { if (self.objectLoader) { RKLogDebug(@"Cancelling in progress table load: asked to load with a new object loader."); [self.objectLoader.queue cancelRequest:self.objectLoader]; } - + theObjectLoader.delegate = self; self.objectLoader = theObjectLoader; } @@ -1337,7 +1442,8 @@ - (void)loadTableWithObjectLoader:(RKObjectLoader *)theObjectLoader { } } -- (void)reloadRowForObject:(id)object withRowAnimation:(UITableViewRowAnimation)rowAnimation { +- (void)reloadRowForObject:(id)object withRowAnimation:(UITableViewRowAnimation)rowAnimation +{ NSIndexPath *indexPath = [self indexPathForObject:object]; if (indexPath) { [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:rowAnimation]; diff --git a/Code/UI/RKAbstractTableController_Internals.h b/Code/UI/RKAbstractTableController_Internals.h index 97c7b42be0..4c721f452f 100644 --- a/Code/UI/RKAbstractTableController_Internals.h +++ b/Code/UI/RKAbstractTableController_Internals.h @@ -69,7 +69,7 @@ Returns a Boolean value indicating if the table controller should be considered empty and transitioned into the empty state. Used by the abstract table controller to trigger state transitions. - + **NOTE**: This is an abstract method that MUST be implemented with a subclass. */ diff --git a/Code/UI/RKControlTableItem.m b/Code/UI/RKControlTableItem.m index c09cd4fbc1..cea55c6499 100644 --- a/Code/UI/RKControlTableItem.m +++ b/Code/UI/RKControlTableItem.m @@ -26,13 +26,15 @@ @implementation RKControlTableItem @synthesize control = _control; -+ (id)tableItemWithControl:(UIControl *)control { ++ (id)tableItemWithControl:(UIControl *)control +{ RKControlTableItem *tableItem = [self tableItem]; tableItem.control = control; return tableItem; } -- (id)init { +- (id)init +{ self = [super init]; if (self) { self.cellMapping.selectionStyle = UITableViewCellSelectionStyleNone; @@ -50,12 +52,14 @@ - (id)init { return self; } -- (void)dealloc { +- (void)dealloc +{ [_control release]; [super dealloc]; } -- (void)setControl:(UIControl *)control { +- (void)setControl:(UIControl *)control +{ NSAssert(control, @"Cannot add a nil control to a RKControlTableItem"); [control retain]; [_control release]; @@ -64,29 +68,35 @@ - (void)setControl:(UIControl *)control { #pragma mark - Convenience Accessors -- (UIButton *)button { - return ([self.control isKindOfClass:[UIButton class]]) ? (UIButton *) self.control : nil; +- (UIButton *)button +{ + return ([self.control isKindOfClass:[UIButton class]]) ? (UIButton *)self.control : nil; } -- (UITextField *)textField { - return ([self.control isKindOfClass:[UITextField class]]) ? (UITextField *) self.control : nil; +- (UITextField *)textField +{ + return ([self.control isKindOfClass:[UITextField class]]) ? (UITextField *)self.control : nil; } -- (UISwitch *)switchControl { - return ([self.control isKindOfClass:[UISwitch class]]) ? (UISwitch *) self.control : nil; +- (UISwitch *)switchControl +{ + return ([self.control isKindOfClass:[UISwitch class]]) ? (UISwitch *)self.control : nil; } -- (UISlider *)slider { - return ([self.control isKindOfClass:[UISlider class]]) ? (UISlider *) self.control : nil; +- (UISlider *)slider +{ + return ([self.control isKindOfClass:[UISlider class]]) ? (UISlider *)self.control : nil; } -- (UILabel *)label { - return ([self.control isKindOfClass:[UILabel class]]) ? (UILabel *) self.control : nil; +- (UILabel *)label +{ + return ([self.control isKindOfClass:[UILabel class]]) ? (UILabel *)self.control : nil; } // TODO: What if we replace this with a protocol that enables KVC // via the 'controlValue' property for the common types to allow pluggability? -- (id)controlValue { +- (id)controlValue +{ if ([self.control isKindOfClass:[UIButton class]]) { return nil; } else if ([self.control isKindOfClass:[UITextField class]]) { diff --git a/Code/UI/RKControlTableViewCell.m b/Code/UI/RKControlTableViewCell.m index 046419c7ba..4c21329f39 100644 --- a/Code/UI/RKControlTableViewCell.m +++ b/Code/UI/RKControlTableViewCell.m @@ -24,7 +24,8 @@ @implementation RKControlTableViewCell @synthesize control; -- (void)layoutSubviews { +- (void)layoutSubviews +{ [super layoutSubviews]; if (self.control.superview != self.contentView) { diff --git a/Code/UI/RKFetchedResultsTableController.h b/Code/UI/RKFetchedResultsTableController.h index 127a212f47..37b4bd4418 100755 --- a/Code/UI/RKFetchedResultsTableController.h +++ b/Code/UI/RKFetchedResultsTableController.h @@ -38,8 +38,6 @@ typedef UIView *(^RKFetchedResultsTableViewViewForHeaderInSectionBlock)(NSUInteg */ @interface RKFetchedResultsTableController : RKAbstractTableController { @private - NSFetchedResultsController *_fetchedResultsController; - BOOL _showsSectionIndexTitles; NSArray *_arraySortedFetchedObjects; BOOL _isEmptyBeforeAnimation; } diff --git a/Code/UI/RKFetchedResultsTableController.m b/Code/UI/RKFetchedResultsTableController.m index c564f99d58..da8fe314e2 100755 --- a/Code/UI/RKFetchedResultsTableController.m +++ b/Code/UI/RKFetchedResultsTableController.m @@ -54,7 +54,8 @@ @implementation RKFetchedResultsTableController @synthesize sortComparator = _sortComparator; @synthesize fetchRequest = _fetchRequest; -- (void)dealloc { +- (void)dealloc +{ _fetchedResultsController.delegate = nil; [_fetchedResultsController release]; _fetchedResultsController = nil; @@ -79,7 +80,8 @@ - (void)dealloc { #pragma mark - Helpers -- (BOOL)performFetch:(NSError **)error { +- (BOOL)performFetch:(NSError **)error +{ // TODO: We could be doing a KVO on the predicate/sortDescriptors/sectionKeyPath and intelligently deleting the cache [NSFetchedResultsController deleteCacheWithName:_fetchedResultsController.cacheName]; BOOL success = [_fetchedResultsController performFetch:error]; @@ -92,7 +94,7 @@ - (BOOL)performFetch:(NSError **)error { if ([self.delegate respondsToSelector:@selector(tableController:didInsertSectionAtIndex:)]) { [self.delegate tableController:self didInsertSectionAtIndex:index]; } - + if ([self.delegate respondsToSelector:@selector(tableController:didInsertObject:atIndexPath:)]) { for (NSUInteger row = 0; row < [self numberOfRowsInSection:index]; row++) { NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:index]; @@ -102,11 +104,12 @@ - (BOOL)performFetch:(NSError **)error { } } } - + return YES; } -- (void)updateSortedArray { +- (void)updateSortedArray +{ [_arraySortedFetchedObjects release]; _arraySortedFetchedObjects = nil; @@ -122,11 +125,13 @@ - (void)updateSortedArray { } } -- (BOOL)isHeaderSection:(NSUInteger)section { +- (BOOL)isHeaderSection:(NSUInteger)section +{ return (section == 0); } -- (BOOL)isHeaderRow:(NSUInteger)row { +- (BOOL)isHeaderRow:(NSUInteger)row +{ BOOL isHeaderRow = NO; NSUInteger headerItemCount = [self.headerItems count]; if ([self isEmpty] && self.emptyItem) { @@ -137,11 +142,13 @@ - (BOOL)isHeaderRow:(NSUInteger)row { return isHeaderRow; } -- (BOOL)isFooterSection:(NSUInteger)section { +- (BOOL)isFooterSection:(NSUInteger)section +{ return (section == ([self sectionCount] - 1)); } -- (BOOL)isFooterRow:(NSUInteger)row { +- (BOOL)isFooterRow:(NSUInteger)row +{ NSUInteger sectionIndex = ([self sectionCount] - 1); id sectionInfo = [[_fetchedResultsController sections] objectAtIndex:sectionIndex]; NSUInteger nonFooterRowCount = [sectionInfo numberOfObjects]; @@ -152,39 +159,46 @@ - (BOOL)isFooterRow:(NSUInteger)row { return (row > (nonFooterRowCount - 1)); } -- (BOOL)isHeaderIndexPath:(NSIndexPath *)indexPath { +- (BOOL)isHeaderIndexPath:(NSIndexPath *)indexPath +{ return ((! [self isEmpty] || self.showsHeaderRowsWhenEmpty) && [self.headerItems count] > 0 && [self isHeaderSection:indexPath.section] && [self isHeaderRow:indexPath.row]); } -- (BOOL)isFooterIndexPath:(NSIndexPath *)indexPath { +- (BOOL)isFooterIndexPath:(NSIndexPath *)indexPath +{ return ((! [self isEmpty] || self.showsFooterRowsWhenEmpty) && [self.footerItems count] > 0 && [self isFooterSection:indexPath.section] && [self isFooterRow:indexPath.row]); } -- (BOOL)isEmptySection:(NSUInteger)section { +- (BOOL)isEmptySection:(NSUInteger)section +{ return (section == 0); } -- (BOOL)isEmptyRow:(NSUInteger)row { +- (BOOL)isEmptyRow:(NSUInteger)row +{ return (row == 0); } -- (BOOL)isEmptyItemIndexPath:(NSIndexPath *)indexPath { +- (BOOL)isEmptyItemIndexPath:(NSIndexPath *)indexPath +{ return ([self isEmpty] && self.emptyItem && [self isEmptySection:indexPath.section] && [self isEmptyRow:indexPath.row]); } -- (NSIndexPath *)emptyItemIndexPath { +- (NSIndexPath *)emptyItemIndexPath +{ return [NSIndexPath indexPathForRow:0 inSection:0]; } -- (NSIndexPath *)fetchedResultsIndexPathForIndexPath:(NSIndexPath *)indexPath { +- (NSIndexPath *)fetchedResultsIndexPathForIndexPath:(NSIndexPath *)indexPath +{ if (([self isEmpty] && self.emptyItem && [self isEmptySection:indexPath.section] && ! [self isEmptyRow:indexPath.row]) || @@ -203,7 +217,8 @@ - (NSIndexPath *)fetchedResultsIndexPathForIndexPath:(NSIndexPath *)indexPath { return indexPath; } -- (NSIndexPath *)indexPathForFetchedResultsIndexPath:(NSIndexPath *)indexPath { +- (NSIndexPath *)indexPathForFetchedResultsIndexPath:(NSIndexPath *)indexPath +{ if (([self isEmpty] && self.emptyItem && [self isEmptySection:indexPath.section] && ! [self isEmptyRow:indexPath.row]) || @@ -223,11 +238,13 @@ - (NSIndexPath *)indexPathForFetchedResultsIndexPath:(NSIndexPath *)indexPath { #pragma mark - Public -- (NSFetchRequest *)fetchRequest { +- (NSFetchRequest *)fetchRequest +{ return _fetchRequest ? _fetchRequest : _fetchedResultsController.fetchRequest; } -- (void)loadTable { +- (void)loadTable +{ NSFetchRequest *fetchRequest = nil; if (_resourcePath) { fetchRequest = [self.objectManager.mappingProvider fetchRequestForResourcePath:self.resourcePath]; @@ -243,12 +260,13 @@ - (void)loadTable { [fetchRequest setSortDescriptors:_sortDescriptors]; } - _fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest + self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:[NSManagedObjectContext contextForCurrentThread] sectionNameKeyPath:_sectionNameKeyPath cacheName:_cacheName]; - _fetchedResultsController.delegate = self; - + [self.fetchedResultsController release]; + self.fetchedResultsController.delegate = self; + // Perform the load NSError *error; [self didStartLoad]; @@ -267,13 +285,15 @@ - (void)loadTable { } } -- (void)setSortSelector:(SEL)sortSelector { +- (void)setSortSelector:(SEL)sortSelector +{ NSAssert(_sectionNameKeyPath == nil, @"Attempted to sort fetchedObjects across multiple sections"); NSAssert(_sortComparator == nil, @"Attempted to sort fetchedObjects with a sortSelector when a sortComparator already exists"); _sortSelector = sortSelector; } -- (void)setSortComparator:(NSComparator)sortComparator { +- (void)setSortComparator:(NSComparator)sortComparator +{ NSAssert(_sectionNameKeyPath == nil, @"Attempted to sort fetchedObjects across multiple sections"); NSAssert(_sortSelector == nil, @"Attempted to sort fetchedObjects with a sortComparator when a sortSelector already exists"); if (_sortComparator) { @@ -283,7 +303,8 @@ - (void)setSortComparator:(NSComparator)sortComparator { _sortComparator = Block_copy(sortComparator); } -- (void)setSectionNameKeyPath:(NSString*)sectionNameKeyPath { +- (void)setSectionNameKeyPath:(NSString *)sectionNameKeyPath +{ NSAssert(_sortSelector == nil, @"Attempted to create a sectioned fetchedResultsController when a sortSelector is present"); NSAssert(_sortComparator == nil, @"Attempted to create a sectioned fetchedResultsController when a sortComparator is present"); [sectionNameKeyPath retain]; @@ -291,14 +312,16 @@ - (void)setSectionNameKeyPath:(NSString*)sectionNameKeyPath { _sectionNameKeyPath = sectionNameKeyPath; } -- (void)setResourcePath:(NSString*)resourcePath { +- (void)setResourcePath:(NSString *)resourcePath +{ [_resourcePath release]; _resourcePath = [resourcePath copy]; self.objectLoader = [self.objectManager loaderWithResourcePath:_resourcePath]; self.objectLoader.delegate = self; } -- (void)setObjectMappingForClass:(Class)objectClass { +- (void)setObjectMappingForClass:(Class)objectClass +{ NSParameterAssert(objectClass != NULL); NSAssert(self.objectLoader != NULL, @"Resource path (and thus object loader) must be set before setting object mapping."); NSAssert(self.objectManager != NULL, @"Object manager must exist before setting object mapping."); @@ -307,11 +330,13 @@ - (void)setObjectMappingForClass:(Class)objectClass { #pragma mark - Managing Sections -- (NSUInteger)sectionCount { +- (NSUInteger)sectionCount +{ return [[_fetchedResultsController sections] count]; } -- (NSUInteger)rowCount { +- (NSUInteger)rowCount +{ NSUInteger fetchedItemCount = [[_fetchedResultsController fetchedObjects] count]; NSUInteger nonFetchedItemCount = 0; if (fetchedItemCount == 0) { @@ -325,19 +350,20 @@ - (NSUInteger)rowCount { return (fetchedItemCount + nonFetchedItemCount); } -- (UITableViewCell *)cellForObjectAtIndexPath:(NSIndexPath *)indexPath { +- (UITableViewCell *)cellForObjectAtIndexPath:(NSIndexPath *)indexPath +{ id mappableObject = [self objectForRowAtIndexPath:indexPath]; NSAssert(mappableObject, @"Cannot build a tableView cell without an object"); - RKTableViewCellMapping* cellMapping = [self.cellMappings cellMappingForObject:mappableObject]; + RKTableViewCellMapping *cellMapping = [self.cellMappings cellMappingForObject:mappableObject]; NSAssert(cellMapping, @"Cannot build a tableView cell for object %@: No cell mapping defined for objects of type '%@'", mappableObject, NSStringFromClass([mappableObject class])); - UITableViewCell* cell = [cellMapping mappableObjectForData:self.tableView]; + UITableViewCell *cell = [cellMapping mappableObjectForData:self.tableView]; NSAssert(cell, @"Cell mapping failed to dequeue or allocate a tableViewCell for object: %@", mappableObject); // Map the object state into the cell - RKObjectMappingOperation* mappingOperation = [[RKObjectMappingOperation alloc] initWithSourceObject:mappableObject destinationObject:cell mapping:cellMapping]; - NSError* error = nil; + RKObjectMappingOperation *mappingOperation = [[RKObjectMappingOperation alloc] initWithSourceObject:mappableObject destinationObject:cell mapping:cellMapping]; + NSError *error = nil; BOOL success = [mappingOperation performMapping:&error]; [mappingOperation release]; @@ -352,26 +378,30 @@ - (UITableViewCell *)cellForObjectAtIndexPath:(NSIndexPath *)indexPath { return cell; } -- (NSIndexPath *)indexPathForObject:(id)object { +- (NSIndexPath *)indexPathForObject:(id)object +{ if ([object isKindOfClass:[NSManagedObject class]]) { return [self indexPathForFetchedResultsIndexPath:[_fetchedResultsController indexPathForObject:object]]; } return nil; } -- (UITableViewCell *)cellForObject:(id)object { +- (UITableViewCell *)cellForObject:(id)object +{ return [self cellForObjectAtIndexPath:[self indexPathForObject:object]]; } #pragma mark - UITableViewDataSource methods -- (NSInteger)numberOfSectionsInTableView:(UITableView*)theTableView { +- (NSInteger)numberOfSectionsInTableView:(UITableView *)theTableView +{ NSAssert(theTableView == self.tableView, @"numberOfSectionsInTableView: invoked with inappropriate tableView: %@", theTableView); RKLogTrace(@"numberOfSectionsInTableView: %d (%@)", [[_fetchedResultsController sections] count], [[_fetchedResultsController sections] valueForKey:@"name"]); return [[_fetchedResultsController sections] count]; } -- (NSInteger)tableView:(UITableView*)theTableView numberOfRowsInSection:(NSInteger)section { +- (NSInteger)tableView:(UITableView *)theTableView numberOfRowsInSection:(NSInteger)section +{ NSAssert(theTableView == self.tableView, @"tableView:numberOfRowsInSection: invoked with inappropriate tableView: %@", theTableView); RKLogTrace(@"%@ numberOfRowsInSection:%d = %d", self, section, self.sectionCount); id sectionInfo = [[_fetchedResultsController sections] objectAtIndex:section]; @@ -387,38 +417,43 @@ - (NSInteger)tableView:(UITableView*)theTableView numberOfRowsInSection:(NSInteg return numberOfRows; } -- (NSString*)tableView:(UITableView*)theTableView titleForHeaderInSection:(NSInteger)section { +- (NSString *)tableView:(UITableView *)theTableView titleForHeaderInSection:(NSInteger)section +{ id sectionInfo = [[_fetchedResultsController sections] objectAtIndex:section]; return [sectionInfo name]; } -- (NSString*)tableView:(UITableView*)theTableView titleForFooterInSection:(NSInteger)section { +- (NSString *)tableView:(UITableView *)theTableView titleForFooterInSection:(NSInteger)section +{ NSAssert(theTableView == self.tableView, @"tableView:titleForFooterInSection: invoked with inappropriate tableView: %@", theTableView); return nil; } -- (NSArray*)sectionIndexTitlesForTableView:(UITableView*)theTableView { +- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)theTableView +{ if (theTableView.style == UITableViewStylePlain && self.showsSectionIndexTitles) { return [_fetchedResultsController sectionIndexTitles]; } return nil; } -- (NSInteger)tableView:(UITableView*)theTableView sectionForSectionIndexTitle:(NSString*)title atIndex:(NSInteger)index { +- (NSInteger)tableView:(UITableView *)theTableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index +{ if (theTableView.style == UITableViewStylePlain && self.showsSectionIndexTitles) { return [_fetchedResultsController sectionForSectionIndexTitle:title atIndex:index]; } return 0; } -- (void)tableView:(UITableView*)theTableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { +- (void)tableView:(UITableView *)theTableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath +{ NSAssert(theTableView == self.tableView, @"tableView:commitEditingStyle:forRowAtIndexPath: invoked with inappropriate tableView: %@", theTableView); if (self.canEditRows && editingStyle == UITableViewCellEditingStyleDelete) { - NSManagedObject* managedObject = [self objectForRowAtIndexPath:indexPath]; - RKObjectMapping* mapping = [[RKObjectManager sharedManager].mappingProvider objectMappingForClass:[managedObject class]]; + NSManagedObject *managedObject = [self objectForRowAtIndexPath:indexPath]; + RKObjectMapping *mapping = [[RKObjectManager sharedManager].mappingProvider objectMappingForClass:[managedObject class]]; if ([mapping isKindOfClass:[RKManagedObjectMapping class]]) { - RKManagedObjectMapping* managedObjectMapping = (RKManagedObjectMapping*)mapping; - NSString* primaryKeyAttribute = managedObjectMapping.primaryKeyAttribute; + RKManagedObjectMapping *managedObjectMapping = (RKManagedObjectMapping *)mapping; + NSString *primaryKeyAttribute = managedObjectMapping.primaryKeyAttribute; if ([managedObject valueForKeyPath:primaryKeyAttribute]) { RKLogTrace(@"About to fire a delete request for managedObject: %@", managedObject); @@ -427,7 +462,7 @@ - (void)tableView:(UITableView*)theTableView commitEditingStyle:(UITableViewCell RKLogTrace(@"About to locally delete managedObject: %@", managedObject); [managedObject.managedObjectContext deleteObject:managedObject]; - NSError* error = nil; + NSError *error = nil; [managedObject.managedObjectContext save:&error]; if (error) { RKLogError(@"Failed to save managedObjectContext after a delete with error: %@", error); @@ -437,36 +472,42 @@ - (void)tableView:(UITableView*)theTableView commitEditingStyle:(UITableViewCell } } -- (void)tableView:(UITableView*)theTableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destIndexPath { +- (void)tableView:(UITableView *)theTableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destIndexPath +{ NSAssert(theTableView == self.tableView, @"tableView:moveRowAtIndexPath:toIndexPath: invoked with inappropriate tableView: %@", theTableView); } -- (BOOL)tableView:(UITableView*)theTableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { +- (BOOL)tableView:(UITableView *)theTableView canEditRowAtIndexPath:(NSIndexPath *)indexPath +{ NSAssert(theTableView == self.tableView, @"tableView:canEditRowAtIndexPath: invoked with inappropriate tableView: %@", theTableView); return self.canEditRows && [self isOnline] && !([self isHeaderIndexPath:indexPath] || [self isFooterIndexPath:indexPath] || [self isEmptyItemIndexPath:indexPath]); } -- (BOOL)tableView:(UITableView*)theTableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath { +- (BOOL)tableView:(UITableView *)theTableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath +{ NSAssert(theTableView == self.tableView, @"tableView:canMoveRowAtIndexPath: invoked with inappropriate tableView: %@", theTableView); return self.canMoveRows && !([self isHeaderIndexPath:indexPath] || [self isFooterIndexPath:indexPath] || [self isEmptyItemIndexPath:indexPath]); } #pragma mark - UITableViewDelegate methods -- (CGFloat)tableView:(UITableView*)theTableView heightForHeaderInSection:(NSInteger)section { +- (CGFloat)tableView:(UITableView *)theTableView heightForHeaderInSection:(NSInteger)section +{ NSAssert(theTableView == self.tableView, @"heightForHeaderInSection: invoked with inappropriate tableView: %@", theTableView); return _heightForHeaderInSection; } -- (CGFloat)tableView:(UITableView*)theTableView heightForFooterInSection:(NSInteger)sectionIndex { +- (CGFloat)tableView:(UITableView *)theTableView heightForFooterInSection:(NSInteger)sectionIndex +{ NSAssert(theTableView == self.tableView, @"heightForFooterInSection: invoked with inappropriate tableView: %@", theTableView); return 0; } -- (UIView*)tableView:(UITableView*)theTableView viewForHeaderInSection:(NSInteger)section { +- (UIView *)tableView:(UITableView *)theTableView viewForHeaderInSection:(NSInteger)section +{ NSAssert(theTableView == self.tableView, @"viewForHeaderInSection: invoked with inappropriate tableView: %@", theTableView); if (_onViewForHeaderInSection) { - NSString* sectionTitle = [self tableView:self.tableView titleForHeaderInSection:section]; + NSString *sectionTitle = [self tableView:self.tableView titleForHeaderInSection:section]; if (sectionTitle) { return _onViewForHeaderInSection(section, sectionTitle); } @@ -474,14 +515,16 @@ - (UIView*)tableView:(UITableView*)theTableView viewForHeaderInSection:(NSIntege return nil; } -- (UIView*)tableView:(UITableView*)theTableView viewForFooterInSection:(NSInteger)sectionIndex { +- (UIView *)tableView:(UITableView *)theTableView viewForFooterInSection:(NSInteger)sectionIndex +{ NSAssert(theTableView == self.tableView, @"viewForFooterInSection: invoked with inappropriate tableView: %@", theTableView); return nil; } #pragma mark - Cell Mappings -- (id)objectForRowAtIndexPath:(NSIndexPath *)indexPath { +- (id)objectForRowAtIndexPath:(NSIndexPath *)indexPath +{ if ([self isEmptyItemIndexPath:indexPath]) { return self.emptyItem; @@ -506,7 +549,8 @@ - (id)objectForRowAtIndexPath:(NSIndexPath *)indexPath { #pragma mark - Network Table Loading -- (void)loadTableFromNetwork { +- (void)loadTableFromNetwork +{ NSAssert(self.objectManager, @"Cannot perform a network load without an object manager"); NSAssert(self.objectLoader, @"Cannot perform a network load when a network load is already in-progress"); RKLogTrace(@"About to loadTableWithObjectLoader..."); @@ -515,7 +559,8 @@ - (void)loadTableFromNetwork { #pragma mark - KVO & Model States -- (BOOL)isConsideredEmpty { +- (BOOL)isConsideredEmpty +{ NSUInteger fetchedObjectsCount = [[_fetchedResultsController fetchedObjects] count]; BOOL isEmpty = (fetchedObjectsCount == 0); RKLogTrace(@"Determined isEmpty = %@. fetchedObjects count = %d", isEmpty ? @"YES" : @"NO", fetchedObjectsCount); @@ -524,7 +569,8 @@ - (BOOL)isConsideredEmpty { #pragma mark - NSFetchedResultsControllerDelegate methods -- (void)controllerWillChangeContent:(NSFetchedResultsController*)controller { +- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller +{ RKLogTrace(@"Beginning updates for fetchedResultsController (%@). Current section count = %d (resource path: %@)", controller, [[controller sections] count], _resourcePath); if (_sortSelector) return; @@ -533,10 +579,11 @@ - (void)controllerWillChangeContent:(NSFetchedResultsController*)controller { _isEmptyBeforeAnimation = [self isEmpty]; } -- (void)controller:(NSFetchedResultsController*)controller +- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id)sectionInfo atIndex:(NSUInteger)sectionIndex - forChangeType:(NSFetchedResultsChangeType)type { + forChangeType:(NSFetchedResultsChangeType)type +{ if (_sortSelector) return; @@ -544,7 +591,7 @@ - (void)controller:(NSFetchedResultsController*)controller case NSFetchedResultsChangeInsert: [self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade]; - + if ([self.delegate respondsToSelector:@selector(tableController:didInsertSectionAtIndex:)]) { [self.delegate tableController:self didInsertSectionAtIndex:sectionIndex]; } @@ -553,7 +600,7 @@ - (void)controller:(NSFetchedResultsController*)controller case NSFetchedResultsChangeDelete: [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade]; - + if ([self.delegate respondsToSelector:@selector(tableController:didDeleteSectionAtIndex:)]) { [self.delegate tableController:self didDeleteSectionAtIndex:sectionIndex]; } @@ -565,16 +612,17 @@ - (void)controller:(NSFetchedResultsController*)controller } } -- (void)controller:(NSFetchedResultsController*)controller +- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type - newIndexPath:(NSIndexPath *)newIndexPath { + newIndexPath:(NSIndexPath *)newIndexPath +{ if (_sortSelector) return; - NSIndexPath* adjIndexPath = [self indexPathForFetchedResultsIndexPath:indexPath]; - NSIndexPath* adjNewIndexPath = [self indexPathForFetchedResultsIndexPath:newIndexPath]; + NSIndexPath *adjIndexPath = [self indexPathForFetchedResultsIndexPath:indexPath]; + NSIndexPath *adjNewIndexPath = [self indexPathForFetchedResultsIndexPath:newIndexPath]; switch (type) { case NSFetchedResultsChangeInsert: @@ -608,7 +656,8 @@ - (void)controller:(NSFetchedResultsController*)controller } } -- (void)controllerDidChangeContent:(NSFetchedResultsController*)controller { +- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller +{ RKLogTrace(@"Ending updates for fetchedResultsController (%@). New section count = %d (resource path: %@)", controller, [[controller sections] count], _resourcePath); if (self.emptyItem && ![self isEmpty] && _isEmptyBeforeAnimation) { @@ -623,21 +672,23 @@ - (void)controllerDidChangeContent:(NSFetchedResultsController*)controller { } else { [self.tableView endUpdates]; } - + [self didFinishLoad]; } #pragma mark - UITableViewDataSource methods -- (UITableViewCell *)tableView:(UITableView*)theTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { +- (UITableViewCell *)tableView:(UITableView *)theTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath +{ NSAssert(theTableView == self.tableView, @"tableView:cellForRowAtIndexPath: invoked with inappropriate tableView: %@", theTableView); - UITableViewCell* cell = [self cellForObjectAtIndexPath:indexPath]; + UITableViewCell *cell = [self cellForObjectAtIndexPath:indexPath]; RKLogTrace(@"%@ cellForRowAtIndexPath:%@ = %@", self, indexPath, cell); return cell; } -- (NSUInteger)numberOfRowsInSection:(NSUInteger)index { +- (NSUInteger)numberOfRowsInSection:(NSUInteger)index +{ return [self tableView:self.tableView numberOfRowsInSection:index]; } diff --git a/Code/UI/RKForm.h b/Code/UI/RKForm.h index 8405bc362d..f3b3d25e00 100644 --- a/Code/UI/RKForm.h +++ b/Code/UI/RKForm.h @@ -46,7 +46,7 @@ typedef void(^RKFormBlock)(); */ @property (nonatomic, readonly) id object; // The table view we are bound to. not retained. -@property (nonatomic, readonly) RKTableController* tableController; +@property (nonatomic, readonly) RKTableController *tableController; //@property (nonatomic, assign) id delegate; @property (nonatomic, copy) RKFormBlock onSubmit; @@ -82,7 +82,7 @@ typedef void(^RKFormBlock)(); - (void)addRowMappingAttribute:(NSString *)attributeKeyPath toKeyPath:(NSString *)controlKeyPath onControl:(UIControl *)control; - (void)addRowMappingAttribute:(NSString *)attributeKeyPath toKeyPath:(NSString *)controlKeyPath onControl:(UIControl *)control usingBlock:(void (^)(RKControlTableItem *tableItem))block; -// TODO: Should there be a flavor that accepts UIView* and yields an RKTableItem? This would avoid needing to cast to (UIControl *) +// TODO: Should there be a flavor that accepts UIView *and yields an RKTableItem? This would avoid needing to cast to (UIControl *) - (void)addRowMappingAttribute:(NSString *)attributeKeyPath toKeyPath:(NSString *)cellKeyPath onCellWithClass:(Class)cellClass; - (void)addRowMappingAttribute:(NSString *)attributeKeyPath toKeyPath:(NSString *)cellKeyPath onCellWithClass:(Class)cellClass usingBlock:(void (^)(RKTableItem *tableItem))block; diff --git a/Code/UI/RKForm.m b/Code/UI/RKForm.m index 2e7a0428ac..d332eb30f3 100644 --- a/Code/UI/RKForm.m +++ b/Code/UI/RKForm.m @@ -39,17 +39,20 @@ @implementation RKForm @synthesize object = _object; @synthesize onSubmit = _onSubmit; -+ (id)formForObject:(id)object { ++ (id)formForObject:(id)object +{ return [[[self alloc] initWithObject:object] autorelease]; } -+ (id)formForObject:(id)object usingBlock:(void (^)(RKForm *))block { ++ (id)formForObject:(id)object usingBlock:(void (^)(RKForm *))block +{ id form = [self formForObject:object]; if (block) block(form); return form; } -- (id)initWithObject:(id)object { +- (id)initWithObject:(id)object +{ if (! object) { [NSException raise:NSInvalidArgumentException format:@"%@ - cannot initialize a form with a nil object", NSStringFromSelector(_cmd)]; @@ -70,7 +73,8 @@ - (id)initWithObject:(id)object { return self; } -- (id)init { +- (id)init +{ self = [super init]; if (self) { _sections = [NSMutableArray new]; @@ -80,7 +84,8 @@ - (id)init { return self; } -- (void)dealloc { +- (void)dealloc +{ [[NSNotificationCenter defaultCenter] removeObserver:self]; [self removeObserverForAttributes]; _tableController = nil; @@ -92,11 +97,13 @@ - (void)dealloc { [super dealloc]; } -- (void)addSection:(RKFormSection *)section { +- (void)addSection:(RKFormSection *)section +{ [_sections addObject:section]; } -- (void)addSectionUsingBlock:(void (^)(RKFormSection *section))block { +- (void)addSectionUsingBlock:(void (^)(RKFormSection *section))block +{ RKFormSection *section = [RKFormSection sectionInForm:self]; block(section); [self addSection:section]; @@ -104,11 +111,13 @@ - (void)addSectionUsingBlock:(void (^)(RKFormSection *section))block { #pragma mark - Table Item Management -- (NSArray *)sections { +- (NSArray *)sections +{ return [NSArray arrayWithArray:_sections]; } -- (RKFormSection *)returnOrInstantiateFirstSection { +- (RKFormSection *)returnOrInstantiateFirstSection +{ if ([_sections count] > 0) { return [_sections objectAtIndex:0]; } @@ -119,7 +128,8 @@ - (RKFormSection *)returnOrInstantiateFirstSection { return section; } -- (NSArray *)tableItems { +- (NSArray *)tableItems +{ NSMutableArray *tableItems = [NSMutableArray array]; for (RKFormSection *section in _sections) { [tableItems addObjectsFromArray:section.objects]; @@ -130,35 +140,43 @@ - (NSArray *)tableItems { #pragma mark - Proxies for Section 0 -- (void)addTableItem:(RKTableItem *)tableItem { +- (void)addTableItem:(RKTableItem *)tableItem +{ [[self returnOrInstantiateFirstSection] addTableItem:tableItem]; } -- (void)addRowForAttribute:(NSString *)attributeKeyPath withControlType:(RKFormControlType)controlType usingBlock:(void (^)(RKControlTableItem *tableItem))block { +- (void)addRowForAttribute:(NSString *)attributeKeyPath withControlType:(RKFormControlType)controlType usingBlock:(void (^)(RKControlTableItem *tableItem))block +{ [[self returnOrInstantiateFirstSection] addRowForAttribute:attributeKeyPath withControlType:controlType usingBlock:block]; } -- (void)addRowForAttribute:(NSString *)attributeKeyPath withControlType:(RKFormControlType)controlType { +- (void)addRowForAttribute:(NSString *)attributeKeyPath withControlType:(RKFormControlType)controlType +{ [self addRowForAttribute:attributeKeyPath withControlType:controlType usingBlock:nil]; } -- (void)addRowMappingAttribute:(NSString *)attributeKeyPath toKeyPath:(NSString *)controlKeyPath onControl:(UIControl *)control usingBlock:(void (^)(RKControlTableItem *tableItem))block { +- (void)addRowMappingAttribute:(NSString *)attributeKeyPath toKeyPath:(NSString *)controlKeyPath onControl:(UIControl *)control usingBlock:(void (^)(RKControlTableItem *tableItem))block +{ [[self returnOrInstantiateFirstSection] addRowMappingAttribute:attributeKeyPath toKeyPath:controlKeyPath onControl:control usingBlock:block]; } -- (void)addRowMappingAttribute:(NSString *)attributeKeyPath toKeyPath:(NSString *)controlKeyPath onControl:(UIControl *)control { +- (void)addRowMappingAttribute:(NSString *)attributeKeyPath toKeyPath:(NSString *)controlKeyPath onControl:(UIControl *)control +{ [self addRowMappingAttribute:attributeKeyPath toKeyPath:controlKeyPath onControl:control usingBlock:nil]; } -- (void)addRowMappingAttribute:(NSString *)attributeKeyPath toKeyPath:(NSString *)cellKeyPath onCellWithClass:(Class)cellClass usingBlock:(void (^)(RKTableItem *tableItem))block { +- (void)addRowMappingAttribute:(NSString *)attributeKeyPath toKeyPath:(NSString *)cellKeyPath onCellWithClass:(Class)cellClass usingBlock:(void (^)(RKTableItem *tableItem))block +{ [[self returnOrInstantiateFirstSection] addRowMappingAttribute:attributeKeyPath toKeyPath:cellKeyPath onCellWithClass:cellClass usingBlock:block]; } -- (void)addRowMappingAttribute:(NSString *)attributeKeyPath toKeyPath:(NSString *)cellKeyPath onCellWithClass:(Class)cellClass { +- (void)addRowMappingAttribute:(NSString *)attributeKeyPath toKeyPath:(NSString *)cellKeyPath onCellWithClass:(Class)cellClass +{ [self addRowMappingAttribute:attributeKeyPath toKeyPath:cellKeyPath onCellWithClass:cellClass usingBlock:nil]; } -- (RKTableItem *)tableItemForAttribute:(NSString *)attributeKeyPath { +- (RKTableItem *)tableItemForAttribute:(NSString *)attributeKeyPath +{ for (RKTableItem *tableItem in self.tableItems) { if ([[tableItem.userData valueForKey:@"__RestKit__attributeKeyPath"] isEqualToString:attributeKeyPath]) { return tableItem; @@ -168,12 +186,14 @@ - (RKTableItem *)tableItemForAttribute:(NSString *)attributeKeyPath { return nil; } -- (RKControlTableItem *)controlTableItemForAttribute:(NSString *)attributeKeyPath { +- (RKControlTableItem *)controlTableItemForAttribute:(NSString *)attributeKeyPath +{ RKTableItem *tableItem = [self tableItemForAttribute:attributeKeyPath]; - return [tableItem isKindOfClass:[RKControlTableItem class]] ? (RKControlTableItem *) tableItem : nil; + return [tableItem isKindOfClass:[RKControlTableItem class]] ? (RKControlTableItem *)tableItem : nil; } -- (UIControl *)controlForAttribute:(NSString *)attributeKeyPath { +- (UIControl *)controlForAttribute:(NSString *)attributeKeyPath +{ RKControlTableItem *tableItem = [self controlTableItemForAttribute:attributeKeyPath]; return tableItem.control; } @@ -187,7 +207,8 @@ - (UIControl *)controlForAttribute:(NSString *)attributeKeyPath { dictionary of the attribute names -> values currently set on the controls. We would then just fire up the mapping operation instead of doing this. It may be cleaner... */ -- (BOOL)commitValuesToObject { +- (BOOL)commitValuesToObject +{ // Serialize the data out of the form RKObjectMapping *objectMapping = [RKObjectMapping mappingForClass:[self.object class]]; NSMutableDictionary *controlValues = [NSMutableDictionary dictionaryWithCapacity:[self.tableItems count]]; @@ -237,7 +258,8 @@ - (BOOL)commitValuesToObject { return success; } -- (void)submit { +- (void)submit +{ if ([self commitValuesToObject]) { // TODO: Add validations? if (self.onSubmit) self.onSubmit(); @@ -246,45 +268,53 @@ - (void)submit { } } -- (void)validate { +- (void)validate +{ // TODO: Implement me at some point... } #pragma mark - Subclass Hooks -- (void)willLoadInTableController:(RKTableController *)tableController { +- (void)willLoadInTableController:(RKTableController *)tableController +{ } -- (void)didLoadInTableController:(RKTableController *)tableController { +- (void)didLoadInTableController:(RKTableController *)tableController +{ _tableController = tableController; } #pragma mark - Key Value Observing -- (void)addObserverForAttribute:(NSString *)attributeKeyPath { +- (void)addObserverForAttribute:(NSString *)attributeKeyPath +{ if (! [_observedAttributes containsObject:attributeKeyPath]) { [self.object addObserver:self forKeyPath:attributeKeyPath options:NSKeyValueObservingOptionNew context:nil]; [_observedAttributes addObject:attributeKeyPath]; } } -- (void)removeObserverForAttribute:(NSString *)attributeKeyPath { +- (void)removeObserverForAttribute:(NSString *)attributeKeyPath +{ if ([_observedAttributes containsObject:attributeKeyPath]) { [self.object removeObserver:self forKeyPath:attributeKeyPath]; [_observedAttributes removeObject:attributeKeyPath]; } } -- (void)removeObserverForAttributes { +- (void)removeObserverForAttributes +{ for (NSString *keyPath in _observedAttributes) { [self.object removeObserver:self forKeyPath:keyPath]; }; [_observedAttributes removeAllObjects]; } -- (void)formSection:(RKFormSection *)formSection didAddTableItem:(RKTableItem *)tableItem forAttributeAtKeyPath:(NSString *)attributeKeyPath { +- (void)formSection:(RKFormSection *)formSection didAddTableItem:(RKTableItem *)tableItem forAttributeAtKeyPath:(NSString *)attributeKeyPath +{ [self addObserverForAttribute:attributeKeyPath]; } -- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { +- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context +{ NSAssert(object == self.object, @"Received unexpected KVO message for object that form is not bound to: %@", object); RKLogTrace(@"Received KVO message for keyPath (%@) for object (%@)", keyPath, object); @@ -295,8 +325,9 @@ - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(N [self.tableController reloadRowForObject:tableItem withRowAnimation:UITableViewRowAnimationFade]; } -- (void)reloadObjectOnContextDidSaveNotification:(NSNotification *)notification { - NSManagedObjectContext *context = (NSManagedObjectContext *) notification.object; +- (void)reloadObjectOnContextDidSaveNotification:(NSNotification *)notification +{ + NSManagedObjectContext *context = (NSManagedObjectContext *)notification.object; NSSet *deletedObjects = [notification.userInfo objectForKey:NSDeletedObjectsKey]; NSSet *updatedObjects = [notification.userInfo objectForKey:NSUpdatedObjectsKey]; diff --git a/Code/UI/RKFormSection.m b/Code/UI/RKFormSection.m index 234b317490..534e78b05d 100644 --- a/Code/UI/RKFormSection.m +++ b/Code/UI/RKFormSection.m @@ -24,11 +24,13 @@ @implementation RKFormSection @synthesize form = _form; -+ (id)sectionInForm:(RKForm *)form { ++ (id)sectionInForm:(RKForm *)form +{ return [[[self alloc] initWithForm:form] autorelease]; } -- (id)initWithForm:(RKForm *)form { +- (id)initWithForm:(RKForm *)form +{ self = [super init]; if (self) { self.form = form; @@ -37,40 +39,43 @@ - (id)initWithForm:(RKForm *)form { return self; } -- (id)object { +- (id)object +{ return self.form.object; } -- (void)addTableItem:(RKTableItem *)tableItem { +- (void)addTableItem:(RKTableItem *)tableItem +{ // We assume if you haven't configured any mappings by // the time the item is added to the section, you probably want the defaults if ([tableItem.cellMapping.attributeMappings count] == 0) { [tableItem.cellMapping addDefaultMappings]; } // TODO: WTF? _objects is declared @protected but using _objects here fails to build... - [(NSMutableArray*)self.objects addObject:tableItem]; + [(NSMutableArray *)self.objects addObject:tableItem]; } -- (UIControl *)controlWithType:(RKFormControlType)controlType { +- (UIControl *)controlWithType:(RKFormControlType)controlType +{ UIControl *control = nil; switch (controlType) { case RKFormControlTypeTextField: case RKFormControlTypeTextFieldSecure:; UITextField *textField = [[[UITextField alloc] init] autorelease]; textField.secureTextEntry = (controlType == RKFormControlTypeTextFieldSecure); - control = (UIControl *) textField; + control = (UIControl *)textField; break; case RKFormControlTypeSwitch:; - control = [(UIControl *) [UISwitch new] autorelease]; + control = [(UIControl *)[UISwitch new] autorelease]; break; case RKFormControlTypeSlider:; - control = [(UIControl *) [UISlider new] autorelease]; + control = [(UIControl *)[UISlider new] autorelease]; break; case RKFormControlTypeLabel:; - control = [(UIControl *) [UILabel new] autorelease]; + control = [(UIControl *)[UILabel new] autorelease]; break; case RKFormControlTypeUnknown: @@ -82,14 +87,15 @@ - (UIControl *)controlWithType:(RKFormControlType)controlType { return control; } -- (NSString *)keyPathForControl:(UIControl *)control { +- (NSString *)keyPathForControl:(UIControl *)control +{ if ([control isKindOfClass:[UITextField class]] || [control isKindOfClass:[UILabel class]]) { return @"text"; } else if ([control isKindOfClass:[UISwitch class]]) { - return @"on"; + return @"on"; } else if ([control isKindOfClass:[UISlider class]]) { - return @"value"; + return @"value"; } else { [NSException raise:NSInvalidArgumentException format:@"*** -[%@ %@]: unable to define mapping for control type %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), NSStringFromClass([control class])]; } @@ -97,7 +103,8 @@ - (NSString *)keyPathForControl:(UIControl *)control { return nil; } -- (void)addAttributeMapping:(RKObjectAttributeMapping *)attributeMapping forKeyPath:(NSString *)attributeKeyPath toTableItem:(RKTableItem *)tableItem { +- (void)addAttributeMapping:(RKObjectAttributeMapping *)attributeMapping forKeyPath:(NSString *)attributeKeyPath toTableItem:(RKTableItem *)tableItem +{ [tableItem.cellMapping addAttributeMapping:attributeMapping]; // Use KVC storage to associate the table item with object being mapped @@ -110,7 +117,8 @@ - (void)addAttributeMapping:(RKObjectAttributeMapping *)attributeMapping forKeyP [self addTableItem:tableItem]; } -- (void)addRowMappingAttribute:(NSString *)attributeKeyPath toKeyPath:(NSString *)controlKeyPath onControl:(UIControl *)control usingBlock:(void (^)(RKControlTableItem *tableItem))block { +- (void)addRowMappingAttribute:(NSString *)attributeKeyPath toKeyPath:(NSString *)controlKeyPath onControl:(UIControl *)control usingBlock:(void (^)(RKControlTableItem *tableItem))block +{ RKControlTableItem *tableItem = [RKControlTableItem tableItemWithControl:control]; RKObjectAttributeMapping *attributeMapping = [[RKObjectAttributeMapping new] autorelease]; attributeMapping.sourceKeyPath = [NSString stringWithFormat:@"userData.__RestKit__object.%@", attributeKeyPath]; @@ -120,21 +128,25 @@ - (void)addRowMappingAttribute:(NSString *)attributeKeyPath toKeyPath:(NSString if (block) block(tableItem); } -- (void)addRowMappingAttribute:(NSString *)attributeKeyPath toKeyPath:(NSString *)controlKeyPath onControl:(UIControl *)control { +- (void)addRowMappingAttribute:(NSString *)attributeKeyPath toKeyPath:(NSString *)controlKeyPath onControl:(UIControl *)control +{ [self addRowMappingAttribute:attributeKeyPath toKeyPath:controlKeyPath onControl:control usingBlock:nil]; } -- (void)addRowForAttribute:(NSString *)attributeKeyPath withControlType:(RKFormControlType)controlType usingBlock:(void (^)(RKControlTableItem *tableItem))block { +- (void)addRowForAttribute:(NSString *)attributeKeyPath withControlType:(RKFormControlType)controlType usingBlock:(void (^)(RKControlTableItem *tableItem))block +{ id control = [self controlWithType:controlType]; NSString *controlKeyPath = [self keyPathForControl:control]; [self addRowMappingAttribute:attributeKeyPath toKeyPath:controlKeyPath onControl:control usingBlock:block]; } -- (void)addRowForAttribute:(NSString *)attributeKeyPath withControlType:(RKFormControlType)controlType { +- (void)addRowForAttribute:(NSString *)attributeKeyPath withControlType:(RKFormControlType)controlType +{ [self addRowForAttribute:attributeKeyPath withControlType:controlType usingBlock:nil]; } -- (void)addRowMappingAttribute:(NSString *)attributeKeyPath toKeyPath:(NSString *)cellKeyPath onCellWithClass:(Class)cellClass usingBlock:(void (^)(RKTableItem *tableItem))block { +- (void)addRowMappingAttribute:(NSString *)attributeKeyPath toKeyPath:(NSString *)cellKeyPath onCellWithClass:(Class)cellClass usingBlock:(void (^)(RKTableItem *tableItem))block +{ RKTableItem *tableItem = [RKTableItem tableItem]; tableItem.cellMapping.cellClass = cellClass; RKObjectAttributeMapping *attributeMapping = [[RKObjectAttributeMapping new] autorelease]; @@ -145,7 +157,8 @@ - (void)addRowMappingAttribute:(NSString *)attributeKeyPath toKeyPath:(NSString if (block) block(tableItem); } -- (void)addRowMappingAttribute:(NSString *)attributeKeyPath toKeyPath:(NSString *)cellKeyPath onCellWithClass:(Class)cellClass { +- (void)addRowMappingAttribute:(NSString *)attributeKeyPath toKeyPath:(NSString *)cellKeyPath onCellWithClass:(Class)cellClass +{ [self addRowMappingAttribute:attributeKeyPath toKeyPath:cellKeyPath onCellWithClass:cellClass usingBlock:nil]; } diff --git a/Code/UI/RKObjectManager+RKTableController.m b/Code/UI/RKObjectManager+RKTableController.m index b0c6b60422..5721bd1869 100644 --- a/Code/UI/RKObjectManager+RKTableController.m +++ b/Code/UI/RKObjectManager+RKTableController.m @@ -15,25 +15,29 @@ @implementation RKObjectManager (RKTableController) -- (RKTableController *)tableControllerForTableViewController:(UITableViewController *)tableViewController { +- (RKTableController *)tableControllerForTableViewController:(UITableViewController *)tableViewController +{ RKTableController *tableController = [RKTableController tableControllerForTableViewController:tableViewController]; tableController.objectManager = self; return tableController; } -- (RKTableController *)tableControllerWithTableView:(UITableView *)tableView forViewController:(UIViewController *)viewController { +- (RKTableController *)tableControllerWithTableView:(UITableView *)tableView forViewController:(UIViewController *)viewController +{ RKTableController *tableController = [RKTableController tableControllerWithTableView:tableView forViewController:viewController]; tableController.objectManager = self; return tableController; } -- (RKFetchedResultsTableController *)fetchedResultsTableControllerForTableViewController:(UITableViewController *)tableViewController { +- (RKFetchedResultsTableController *)fetchedResultsTableControllerForTableViewController:(UITableViewController *)tableViewController +{ RKFetchedResultsTableController *tableController = [RKFetchedResultsTableController tableControllerForTableViewController:tableViewController]; tableController.objectManager = self; return tableController; } -- (RKFetchedResultsTableController *)fetchedResultsTableControllerWithTableView:(UITableView *)tableView forViewController:(UIViewController *)viewController { +- (RKFetchedResultsTableController *)fetchedResultsTableControllerWithTableView:(UITableView *)tableView forViewController:(UIViewController *)viewController +{ RKFetchedResultsTableController *tableController = [RKFetchedResultsTableController tableControllerWithTableView:tableView forViewController:viewController]; return tableController; } diff --git a/Code/UI/RKRefreshGestureRecognizer.h b/Code/UI/RKRefreshGestureRecognizer.h index e3759f9ee8..0e958bd2cf 100644 --- a/Code/UI/RKRefreshGestureRecognizer.h +++ b/Code/UI/RKRefreshGestureRecognizer.h @@ -30,8 +30,8 @@ typedef enum { @protocol RKRefreshTriggerProtocol @optional -- (NSDate*)pullToRefreshDataSourceLastUpdated:(UIGestureRecognizer*)recognizer; -- (BOOL)pullToRefreshDataSourceIsLoading:(UIGestureRecognizer*)recognizer; +- (NSDate *)pullToRefreshDataSourceLastUpdated:(UIGestureRecognizer *)recognizer; +- (BOOL)pullToRefreshDataSourceIsLoading:(UIGestureRecognizer *)recognizer; @end @interface RKRefreshGestureRecognizer : UIGestureRecognizer diff --git a/Code/UI/RKRefreshGestureRecognizer.m b/Code/UI/RKRefreshGestureRecognizer.m index 1a101e2b2c..0917f2992f 100644 --- a/Code/UI/RKRefreshGestureRecognizer.m +++ b/Code/UI/RKRefreshGestureRecognizer.m @@ -47,7 +47,8 @@ @implementation RKRefreshGestureRecognizer @synthesize dateFormatter = _dateFormatter; #pragma mark - Life Cycle -- (id)initWithTarget:(id)target action:(SEL)action { +- (id)initWithTarget:(id)target action:(SEL)action +{ self = [super initWithTarget:target action:action]; if (self) { @@ -61,7 +62,8 @@ - (id)initWithTarget:(id)target action:(SEL)action { return self; } -- (void)dealloc { +- (void)dealloc +{ [self removeObserver:self forKeyPath:@"view"]; if (self.triggerView) [self.triggerView removeFromSuperview]; @@ -71,7 +73,8 @@ - (void)dealloc { #pragma mark - Utilities -- (void)refreshLastUpdatedDate { +- (void)refreshLastUpdatedDate +{ SEL lastUpdatedSelector = @selector(pullToRefreshDataSourceLastUpdated:); if (self.scrollView.delegate && [self.scrollView.delegate respondsToSelector:lastUpdatedSelector]) { @@ -87,7 +90,8 @@ - (void)refreshLastUpdatedDate { } -- (void)setRefreshState:(RKRefreshState)refreshState { +- (void)setRefreshState:(RKRefreshState)refreshState +{ if (refreshState == _refreshState) return; @@ -144,7 +148,8 @@ - (void)setRefreshState:(RKRefreshState)refreshState { _refreshState = refreshState; } -- (CABasicAnimation *)triggeredAnimation { +- (CABasicAnimation *)triggeredAnimation +{ CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"]; animation.duration = kFlipArrowAnimationTime; animation.toValue = [NSNumber numberWithDouble:M_PI]; @@ -153,7 +158,8 @@ - (CABasicAnimation *)triggeredAnimation { return animation; } -- (CABasicAnimation *)idlingAnimation { +- (CABasicAnimation *)idlingAnimation +{ CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"]; animation.delegate = self; animation.duration = kFlipArrowAnimationTime; @@ -162,15 +168,18 @@ - (CABasicAnimation *)idlingAnimation { return animation; } -- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag { +- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag +{ [self.triggerView.arrowView.layer removeAllAnimations]; } -- (UIScrollView *)scrollView { +- (UIScrollView *)scrollView +{ return (UIScrollView *)self.view; } -- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { +- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context +{ id obj = [object valueForKeyPath:keyPath]; if (NO == [obj isKindOfClass:[UIScrollView class]]) { self.isBoundToScrollView = NO; @@ -182,15 +191,18 @@ - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(N } #pragma mark UIGestureRecognizer -- (BOOL)canPreventGestureRecognizer:(UIGestureRecognizer *)preventedGestureRecognizer { +- (BOOL)canPreventGestureRecognizer:(UIGestureRecognizer *)preventedGestureRecognizer +{ return NO; } -- (BOOL)canBePreventedByGestureRecognizer:(UIGestureRecognizer *)preventingGestureRecognizer { +- (BOOL)canBePreventedByGestureRecognizer:(UIGestureRecognizer *)preventingGestureRecognizer +{ return NO; } -- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { +- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event +{ if (!self.isBoundToScrollView) return; if (self.state < UIGestureRecognizerStateBegan) { @@ -206,7 +218,8 @@ - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { } } -- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { +- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event +{ if (!self.isBoundToScrollView) { self.state = UIGestureRecognizerStateFailed; return; @@ -220,7 +233,8 @@ - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { self.refreshState = RKRefreshIdle; } -- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event { +- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event +{ self.state = UIGestureRecognizerStateCancelled; } diff --git a/Code/UI/RKRefreshTriggerView.h b/Code/UI/RKRefreshTriggerView.h index fd30dc6d47..fc0853cf0b 100644 --- a/Code/UI/RKRefreshTriggerView.h +++ b/Code/UI/RKRefreshTriggerView.h @@ -21,20 +21,20 @@ #import -@interface RKRefreshTriggerView : UIView +@interface RKRefreshTriggerView : UIView @property (nonatomic, retain) UILabel *titleLabel; @property (nonatomic, retain) UILabel *lastUpdatedLabel; @property (nonatomic, retain) UIImageView *arrowView; @property (nonatomic, retain) UIActivityIndicatorView *activityView; #ifdef UI_APPEARANCE_SELECTOR -@property (nonatomic,assign) UIImage *arrowImage UI_APPEARANCE_SELECTOR; -@property (nonatomic,assign) UIActivityIndicatorViewStyle activityIndicatorStyle UI_APPEARANCE_SELECTOR; -@property (nonatomic,assign) UIFont *titleFont UI_APPEARANCE_SELECTOR; -@property (nonatomic,assign) UIColor *titleColor UI_APPEARANCE_SELECTOR; -@property (nonatomic,assign) UIFont *lastUpdatedFont UI_APPEARANCE_SELECTOR; -@property (nonatomic,assign) UIColor *lastUpdatedColor UI_APPEARANCE_SELECTOR; -@property (nonatomic,retain) UIColor *refreshBackgroundColor UI_APPEARANCE_SELECTOR; +@property (nonatomic, assign) UIImage *arrowImage UI_APPEARANCE_SELECTOR; +@property (nonatomic, assign) UIActivityIndicatorViewStyle activityIndicatorStyle UI_APPEARANCE_SELECTOR; +@property (nonatomic, assign) UIFont *titleFont UI_APPEARANCE_SELECTOR; +@property (nonatomic, assign) UIColor *titleColor UI_APPEARANCE_SELECTOR; +@property (nonatomic, assign) UIFont *lastUpdatedFont UI_APPEARANCE_SELECTOR; +@property (nonatomic, assign) UIColor *lastUpdatedColor UI_APPEARANCE_SELECTOR; +@property (nonatomic, retain) UIColor *refreshBackgroundColor UI_APPEARANCE_SELECTOR; #endif @end diff --git a/Code/UI/RKRefreshTriggerView.m b/Code/UI/RKRefreshTriggerView.m index 327d402da1..0bb10e52e1 100644 --- a/Code/UI/RKRefreshTriggerView.m +++ b/Code/UI/RKRefreshTriggerView.m @@ -72,7 +72,8 @@ - (id)initWithFrame:(CGRect)frame } -- (void)dealloc { +- (void)dealloc +{ self.titleLabel = nil; self.arrowView = nil; self.activityView = nil; @@ -81,96 +82,111 @@ - (void)dealloc { } -- (void)layoutSubviews { +- (void)layoutSubviews +{ CGPoint imageCenter = CGPointMake(30, CGRectGetMidY(self.bounds)); self.arrowView.center = imageCenter; self.arrowView.frame = CGRectIntegral(self.arrowView.frame); self.activityView.center = imageCenter; - self.titleLabel.frame = CGRectIntegral(CGRectMake(0.0f, ( CGRectGetHeight(self.bounds) * .25f ), CGRectGetWidth(self.bounds), 20.0f)); - self.lastUpdatedLabel.frame = CGRectOffset(self.titleLabel.frame, 0.f, 18.f ); + self.titleLabel.frame = CGRectIntegral(CGRectMake(0.0f, (CGRectGetHeight(self.bounds) * .25f), CGRectGetWidth(self.bounds), 20.0f)); + self.lastUpdatedLabel.frame = CGRectOffset(self.titleLabel.frame, 0.f, 18.f); } #ifdef UI_APPEARANCE_SELECTOR #pragma mark - Proxy Accessors for UIAppearance -- (UIImage *)arrowImage { +- (UIImage *)arrowImage +{ if (!self.arrowView) return DEFAULT_REFRESH_ARROW_IMAGE; return _arrowView.image; } -- (void)setArrowImage:(UIImage *)image { +- (void)setArrowImage:(UIImage *)image +{ if (!self.arrowView) return; self.arrowView.image = image; } -- (UIActivityIndicatorViewStyle)activityIndicatorStyle { +- (UIActivityIndicatorViewStyle)activityIndicatorStyle +{ if (!self.activityView) return DEFAULT_REFRESH_ACTIVITY_STYLE; return self.activityView.activityIndicatorViewStyle; } -- (void)setActivityIndicatorStyle:(UIActivityIndicatorViewStyle)style { +- (void)setActivityIndicatorStyle:(UIActivityIndicatorViewStyle)style +{ if (!self.activityView) return; self.activityView.activityIndicatorViewStyle = style; } -- (UIFont *)titleFont { +- (UIFont *)titleFont +{ if (!self.titleLabel) return DEFAULT_REFRESH_TITLE_FONT; return self.titleLabel.font; } -- (void)setTitleFont:(UIFont *)font { +- (void)setTitleFont:(UIFont *)font +{ if (!self.titleLabel) return; self.titleLabel.font = font; } -- (UIColor *)titleColor { +- (UIColor *)titleColor +{ if (!self.titleLabel) return DEFAULT_REFRESH_TITLE_COLOR; return self.titleLabel.textColor; } -- (void)setTitleColor:(UIColor *)color { +- (void)setTitleColor:(UIColor *)color +{ if (!self.titleLabel) return; self.titleLabel.textColor = color; } -- (UIFont *)lastUpdatedFont { +- (UIFont *)lastUpdatedFont +{ if (!self.lastUpdatedLabel) return DEFAULT_REFRESH_UPDATED_FONT; return self.lastUpdatedLabel.font; } -- (void)setLastUpdatedFont:(UIFont *)font { +- (void)setLastUpdatedFont:(UIFont *)font +{ if (!self.lastUpdatedLabel) return; self.lastUpdatedLabel.font = font; } -- (UIColor *)lastUpdatedColor { +- (UIColor *)lastUpdatedColor +{ if (!self.lastUpdatedLabel) return DEFAULT_REFRESH_UPDATED_COLOR; return self.lastUpdatedLabel.textColor; } -- (void)setLastUpdatedColor:(UIColor *)color { +- (void)setLastUpdatedColor:(UIColor *)color +{ if (!self.lastUpdatedLabel) return; self.lastUpdatedLabel.textColor = color; } -- (UIColor *)refreshBackgroundColor { +- (UIColor *)refreshBackgroundColor +{ return self.backgroundColor; } -- (void)setRefreshBackgroundColor:(UIColor *)backgroundColor { +- (void)setRefreshBackgroundColor:(UIColor *)backgroundColor +{ [self setBackgroundColor:backgroundColor]; } #endif diff --git a/Code/UI/RKTableController.h b/Code/UI/RKTableController.h index 9cf8d8ad10..b65928ec18 100644 --- a/Code/UI/RKTableController.h +++ b/Code/UI/RKTableController.h @@ -118,7 +118,7 @@ /** The key path on the loaded objects used to determine the section they belong to. */ -@property(nonatomic, copy) NSString *sectionNameKeyPath; +@property (nonatomic, copy) NSString *sectionNameKeyPath; /** Returns the section at the specified index. @@ -126,7 +126,7 @@ */ - (RKTableSection *)sectionAtIndex:(NSUInteger)index; -/** +/** Returns the first section with the specified header title. @param title The header title. */ @@ -134,7 +134,7 @@ /** Returns the index of the specified section. - + @param section Must be a valid non nil RKTableViewSection. @return The index of the given section if contained within the receiver, otherwise NSNotFound. */ diff --git a/Code/UI/RKTableController.m b/Code/UI/RKTableController.m index eef6248f4f..358b57d65d 100644 --- a/Code/UI/RKTableController.m +++ b/Code/UI/RKTableController.m @@ -42,7 +42,8 @@ @implementation RKTableController #pragma mark - Instantiation -- (id)init { +- (id)init +{ self = [super init]; if (self) { _sections = [NSMutableArray new]; @@ -58,39 +59,46 @@ - (id)init { return self; } -- (void)dealloc { +- (void)dealloc +{ [self removeObserver:self forKeyPath:@"sections"]; [_form release]; [_sectionNameKeyPath release]; [_sections release]; - + [super dealloc]; } #pragma mark - Managing Sections // KVO-compliant proxy object for section mutations -- (NSMutableArray *)sectionsProxy { +- (NSMutableArray *)sectionsProxy +{ return [self mutableArrayValueForKey:@"sections"]; } -- (void)addSectionsObject:(id)section { +- (void)addSectionsObject:(id)section +{ [self.sections addObject:section]; } -- (void)insertSections:(NSArray *)objects atIndexes:(NSIndexSet *)indexes { +- (void)insertSections:(NSArray *)objects atIndexes:(NSIndexSet *)indexes +{ [self.sections insertObjects:objects atIndexes:indexes]; } -- (void)removeSectionsAtIndexes:(NSIndexSet *)indexes { +- (void)removeSectionsAtIndexes:(NSIndexSet *)indexes +{ [self.sections removeObjectsAtIndexes:indexes]; } -- (void)replaceSectionsAtIndexes:(NSIndexSet *)indexes withObjects:(NSArray *)objects { +- (void)replaceSectionsAtIndexes:(NSIndexSet *)indexes withObjects:(NSArray *)objects +{ [self.sections replaceObjectsAtIndexes:indexes withObjects:objects]; } -- (void)addSection:(RKTableSection *)section { +- (void)addSection:(RKTableSection *)section +{ NSAssert(section, @"Cannot insert a nil section"); section.tableController = self; if (! section.cellMappings) { @@ -100,7 +108,8 @@ - (void)addSection:(RKTableSection *)section { [[self sectionsProxy] addObject:section]; } -- (void)removeSection:(RKTableSection *)section { +- (void)removeSection:(RKTableSection *)section +{ NSAssert(section, @"Cannot remove a nil section"); if ([self.sections containsObject:section] && self.sectionCount == 1) { @throw [NSException exceptionWithName:NSInvalidArgumentException @@ -110,13 +119,15 @@ - (void)removeSection:(RKTableSection *)section { [[self sectionsProxy] removeObject:section]; } -- (void)insertSection:(RKTableSection *)section atIndex:(NSUInteger)index { +- (void)insertSection:(RKTableSection *)section atIndex:(NSUInteger)index +{ NSAssert(section, @"Cannot insert a nil section"); section.tableController = self; [[self sectionsProxy] insertObject:section atIndex:index]; } -- (void)removeSectionAtIndex:(NSUInteger)index { +- (void)removeSectionAtIndex:(NSUInteger)index +{ if (index < self.sectionCount && self.sectionCount == 1) { @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"Tables must always have at least one section" @@ -125,7 +136,8 @@ - (void)removeSectionAtIndex:(NSUInteger)index { [[self sectionsProxy] removeObjectAtIndex:index]; } -- (void)removeAllSections:(BOOL)recreateFirstSection { +- (void)removeAllSections:(BOOL)recreateFirstSection +{ [[self sectionsProxy] removeAllObjects]; if (recreateFirstSection) { @@ -133,11 +145,13 @@ - (void)removeAllSections:(BOOL)recreateFirstSection { } } -- (void)removeAllSections { +- (void)removeAllSections +{ [self removeAllSections:YES]; } -- (void)updateTableViewUsingBlock:(void (^)())block { +- (void)updateTableViewUsingBlock:(void (^)())block +{ [self.tableView beginUpdates]; block(); [self.tableView endUpdates]; @@ -145,8 +159,9 @@ - (void)updateTableViewUsingBlock:(void (^)())block { #pragma mark - Static Tables -- (NSArray*)objectsWithHeaderAndFooters:(NSArray *)objects forSection:(NSUInteger)sectionIndex { - NSMutableArray* mutableObjects = [objects mutableCopy]; +- (NSArray *)objectsWithHeaderAndFooters:(NSArray *)objects forSection:(NSUInteger)sectionIndex +{ + NSMutableArray *mutableObjects = [objects mutableCopy]; if (sectionIndex == 0) { if ([self.headerItems count] > 0) { [mutableObjects insertObjects:self.headerItems atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, self.headerItems.count)]]; @@ -164,11 +179,12 @@ - (NSArray*)objectsWithHeaderAndFooters:(NSArray *)objects forSection:(NSUIntege } // NOTE - Everything currently needs to pass through this method to pick up header/footer rows... -- (void)loadObjects:(NSArray *)objects inSection:(NSUInteger)sectionIndex { +- (void)loadObjects:(NSArray *)objects inSection:(NSUInteger)sectionIndex +{ // Clear any existing error state from the table self.error = nil; - RKTableSection* section = [self sectionAtIndex:sectionIndex]; + RKTableSection *section = [self sectionAtIndex:sectionIndex]; section.objects = [self objectsWithHeaderAndFooters:objects forSection:sectionIndex]; for (NSUInteger index = 0; index < [section.objects count]; index++) { if ([self.delegate respondsToSelector:@selector(tableController:didInsertObject:atIndexPath:)]) { @@ -179,11 +195,11 @@ - (void)loadObjects:(NSArray *)objects inSection:(NSUInteger)sectionIndex { } [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:self.defaultRowAnimation]; - + if ([self.delegate respondsToSelector:@selector(tableController:didLoadObjects:inSection:)]) { [self.delegate tableController:self didLoadObjects:objects inSection:section]; } - + // The load is finalized via network callbacks for // dynamic table controllers if (nil == self.objectLoader) { @@ -191,16 +207,19 @@ - (void)loadObjects:(NSArray *)objects inSection:(NSUInteger)sectionIndex { } } -- (void)loadObjects:(NSArray *)objects { +- (void)loadObjects:(NSArray *)objects +{ [self loadObjects:objects inSection:0]; } -- (void)loadEmpty { +- (void)loadEmpty +{ [self removeAllSections:YES]; [self loadObjects:[NSArray array]]; } -- (void)loadTableItems:(NSArray *)tableItems inSection:(NSUInteger)sectionIndex { +- (void)loadTableItems:(NSArray *)tableItems inSection:(NSUInteger)sectionIndex +{ for (RKTableItem *tableItem in tableItems) { if ([tableItem.cellMapping.attributeMappings count] == 0) { [tableItem.cellMapping addDefaultMappings]; @@ -212,40 +231,46 @@ - (void)loadTableItems:(NSArray *)tableItems inSection:(NSUInteger)sectionIndex - (void)loadTableItems:(NSArray *)tableItems inSection:(NSUInteger)sectionIndex - withMapping:(RKTableViewCellMapping *)cellMapping { + withMapping:(RKTableViewCellMapping *)cellMapping +{ NSAssert(tableItems, @"Cannot load a nil collection of table items"); NSAssert(sectionIndex < self.sectionCount, @"Cannot load table items into a section that does not exist"); NSAssert(cellMapping, @"Cannot load table items without a cell mapping"); - for (RKTableItem* tableItem in tableItems) { + for (RKTableItem *tableItem in tableItems) { tableItem.cellMapping = cellMapping; } [self loadTableItems:tableItems inSection:sectionIndex]; } -- (void)loadTableItems:(NSArray *)tableItems withMapping:(RKTableViewCellMapping *)cellMapping { +- (void)loadTableItems:(NSArray *)tableItems withMapping:(RKTableViewCellMapping *)cellMapping +{ [self loadTableItems:tableItems inSection:0 withMapping:cellMapping]; } -- (void)loadTableItems:(NSArray *)tableItems { +- (void)loadTableItems:(NSArray *)tableItems +{ [self loadTableItems:tableItems inSection:0]; } #pragma mark - Network Table Loading -- (void)loadTableFromResourcePath:(NSString*)resourcePath { - NSAssert(self.objectManager, @"Cannot perform a network load without an object manager"); - [self loadTableWithObjectLoader:[self.objectManager loaderWithResourcePath:resourcePath]]; +- (void)loadTableFromResourcePath:(NSString *)resourcePath +{ + [self loadTableFromResourcePath:resourcePath usingBlock:nil]; } -- (void)loadTableFromResourcePath:(NSString *)resourcePath usingBlock:(void (^)(RKObjectLoader *loader))block { - RKObjectLoader* theObjectLoader = [self.objectManager loaderWithResourcePath:resourcePath]; - block(theObjectLoader); - [self loadTableWithObjectLoader:theObjectLoader]; +- (void)loadTableFromResourcePath:(NSString *)resourcePath usingBlock:(void (^)(RKObjectLoader *loader))block +{ + NSAssert(self.objectManager, @"Cannot perform a network load without an object manager"); + RKObjectLoader *objectLoader = [self.objectManager loaderWithResourcePath:resourcePath]; + if (block) block(objectLoader); + [self loadTableWithObjectLoader:objectLoader]; } #pragma mark - Forms -- (void)loadForm:(RKForm *)form { +- (void)loadForm:(RKForm *)form +{ [form retain]; [_form release]; _form = form; @@ -266,11 +291,12 @@ - (void)loadForm:(RKForm *)form { #pragma mark - UITableViewDataSource methods -- (void)tableView:(UITableView*)theTableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { +- (void)tableView:(UITableView *)theTableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath +{ NSAssert(theTableView == self.tableView, @"tableView:commitEditingStyle:forRowAtIndexPath: invoked with inappropriate tableView: %@", theTableView); if (self.canEditRows) { if (editingStyle == UITableViewCellEditingStyleDelete) { - RKTableSection* section = [self.sections objectAtIndex:indexPath.section]; + RKTableSection *section = [self.sections objectAtIndex:indexPath.section]; [section removeObjectAtIndex:indexPath.row]; } else if (editingStyle == UITableViewCellEditingStyleInsert) { @@ -279,20 +305,21 @@ - (void)tableView:(UITableView*)theTableView commitEditingStyle:(UITableViewCell } } -- (void)tableView:(UITableView*)theTableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destIndexPath { +- (void)tableView:(UITableView *)theTableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destIndexPath +{ NSAssert(theTableView == self.tableView, @"tableView:moveRowAtIndexPath:toIndexPath: invoked with inappropriate tableView: %@", theTableView); if (self.canMoveRows) { if (sourceIndexPath.section == destIndexPath.section) { - RKTableSection* section = [self.sections objectAtIndex:sourceIndexPath.section]; + RKTableSection *section = [self.sections objectAtIndex:sourceIndexPath.section]; [section moveObjectAtIndex:sourceIndexPath.row toIndex:destIndexPath.row]; } else { [self.tableView beginUpdates]; - RKTableSection* sourceSection = [self.sections objectAtIndex:sourceIndexPath.section]; + RKTableSection *sourceSection = [self.sections objectAtIndex:sourceIndexPath.section]; id object = [[sourceSection objectAtIndex:sourceIndexPath.row] retain]; [sourceSection removeObjectAtIndex:sourceIndexPath.row]; - RKTableSection* destinationSection = nil; + RKTableSection *destinationSection = nil; if (destIndexPath.section < [self sectionCount]) { destinationSection = [self.sections objectAtIndex:destIndexPath.section]; } else { @@ -308,7 +335,8 @@ - (void)tableView:(UITableView*)theTableView moveRowAtIndexPath:(NSIndexPath *)s #pragma mark - RKRequestDelegate & RKObjectLoaderDelegate methods -- (void)objectLoader:(RKObjectLoader *)loader didLoadObjects:(NSArray *)objects { +- (void)objectLoader:(RKObjectLoader *)loader didLoadObjects:(NSArray *)objects +{ // TODO: Could not get the KVO to work without a boolean property... // TODO: Apply any sorting... @@ -329,7 +357,8 @@ - (void)objectLoader:(RKObjectLoader *)loader didLoadObjects:(NSArray *)objects } } -- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { +- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context +{ [super observeValueForKeyPath:keyPath ofObject:object change:change context:context]; if ([keyPath isEqualToString:@"sections"]) { // No table view to inform... @@ -363,49 +392,56 @@ - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(N #pragma mark - Managing Sections -- (NSUInteger)sectionCount { +- (NSUInteger)sectionCount +{ return [_sections count]; } -- (NSUInteger)rowCount { +- (NSUInteger)rowCount +{ return [[_sections valueForKeyPath:@"@sum.rowCount"] intValue]; } -- (RKTableSection *)sectionAtIndex:(NSUInteger)index { +- (RKTableSection *)sectionAtIndex:(NSUInteger)index +{ return [_sections objectAtIndex:index]; } -- (NSUInteger)indexForSection:(RKTableSection *)section { +- (NSUInteger)indexForSection:(RKTableSection *)section +{ NSAssert(section, @"Cannot return index for a nil section"); return [_sections indexOfObject:section]; } -- (RKTableSection *)sectionWithHeaderTitle:(NSString *)title { - for (RKTableSection* section in _sections) { +- (RKTableSection *)sectionWithHeaderTitle:(NSString *)title +{ + for (RKTableSection *section in _sections) { if ([section.headerTitle isEqualToString:title]) { return section; } } - + return nil; } -- (NSUInteger)numberOfRowsInSection:(NSUInteger)index { +- (NSUInteger)numberOfRowsInSection:(NSUInteger)index +{ return [self sectionAtIndex:index].rowCount; } -- (UITableViewCell *)cellForObjectAtIndexPath:(NSIndexPath *)indexPath { - RKTableSection* section = [self sectionAtIndex:indexPath.section]; +- (UITableViewCell *)cellForObjectAtIndexPath:(NSIndexPath *)indexPath +{ + RKTableSection *section = [self sectionAtIndex:indexPath.section]; id mappableObject = [section objectAtIndex:indexPath.row]; - RKTableViewCellMapping* cellMapping = [self.cellMappings cellMappingForObject:mappableObject]; + RKTableViewCellMapping *cellMapping = [self.cellMappings cellMappingForObject:mappableObject]; NSAssert(cellMapping, @"Cannot build a tableView cell for object %@: No cell mapping defined for objects of type '%@'", mappableObject, NSStringFromClass([mappableObject class])); - - UITableViewCell* cell = [cellMapping mappableObjectForData:self.tableView]; + + UITableViewCell *cell = [cellMapping mappableObjectForData:self.tableView]; NSAssert(cell, @"Cell mapping failed to dequeue or allocate a tableViewCell for object: %@", mappableObject); - + // Map the object state into the cell - RKObjectMappingOperation* mappingOperation = [[RKObjectMappingOperation alloc] initWithSourceObject:mappableObject destinationObject:cell mapping:cellMapping]; - NSError* error = nil; + RKObjectMappingOperation *mappingOperation = [[RKObjectMappingOperation alloc] initWithSourceObject:mappableObject destinationObject:cell mapping:cellMapping]; + NSError *error = nil; BOOL success = [mappingOperation performMapping:&error]; [mappingOperation release]; // NOTE: If there is no mapping work performed, but no error is generated then @@ -415,53 +451,61 @@ - (UITableViewCell *)cellForObjectAtIndexPath:(NSIndexPath *)indexPath { RKLogError(@"Failed to generate table cell for object: %@", error); return nil; } - + return cell; } #pragma mark - Cell Mappings -- (id)objectForRowAtIndexPath:(NSIndexPath *)indexPath { +- (id)objectForRowAtIndexPath:(NSIndexPath *)indexPath +{ NSAssert(indexPath, @"Cannot lookup object with a nil indexPath"); - RKTableSection* section = [self sectionAtIndex:indexPath.section]; + RKTableSection *section = [self sectionAtIndex:indexPath.section]; return [section objectAtIndex:indexPath.row]; } #pragma mark - UITableViewDataSource methods -- (NSString*)tableView:(UITableView*)theTableView titleForHeaderInSection:(NSInteger)section { +- (NSString *)tableView:(UITableView *)theTableView titleForHeaderInSection:(NSInteger)section +{ NSAssert(theTableView == self.tableView, @"tableView:titleForHeaderInSection: invoked with inappropriate tableView: %@", theTableView); return [[_sections objectAtIndex:section] headerTitle]; } -- (NSString*)tableView:(UITableView*)theTableView titleForFooterInSection:(NSInteger)section { +- (NSString *)tableView:(UITableView *)theTableView titleForFooterInSection:(NSInteger)section +{ NSAssert(theTableView == self.tableView, @"tableView:titleForFooterInSection: invoked with inappropriate tableView: %@", theTableView); return [[_sections objectAtIndex:section] footerTitle]; } -- (BOOL)tableView:(UITableView*)theTableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { +- (BOOL)tableView:(UITableView *)theTableView canEditRowAtIndexPath:(NSIndexPath *)indexPath +{ NSAssert(theTableView == self.tableView, @"tableView:canEditRowAtIndexPath: invoked with inappropriate tableView: %@", theTableView); return self.canEditRows; } -- (BOOL)tableView:(UITableView*)theTableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath { +- (BOOL)tableView:(UITableView *)theTableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath +{ NSAssert(theTableView == self.tableView, @"tableView:canMoveRowAtIndexPath: invoked with inappropriate tableView: %@", theTableView); return self.canMoveRows; } -- (NSInteger)numberOfSectionsInTableView:(UITableView*)theTableView { +- (NSInteger)numberOfSectionsInTableView:(UITableView *)theTableView +{ NSAssert(theTableView == self.tableView, @"numberOfSectionsInTableView: invoked with inappropriate tableView: %@", theTableView); RKLogTrace(@"%@ numberOfSectionsInTableView = %d", self, self.sectionCount); return self.sectionCount; } -- (NSInteger)tableView:(UITableView*)theTableView numberOfRowsInSection:(NSInteger)section { +- (NSInteger)tableView:(UITableView *)theTableView numberOfRowsInSection:(NSInteger)section +{ NSAssert(theTableView == self.tableView, @"tableView:numberOfRowsInSection: invoked with inappropriate tableView: %@", theTableView); RKLogTrace(@"%@ numberOfRowsInSection:%d = %d", self, section, self.sectionCount); return [[_sections objectAtIndex:section] rowCount]; } -- (NSIndexPath *)indexPathForObject:(id)object { +- (NSIndexPath *)indexPathForObject:(id)object +{ NSUInteger sectionIndex = 0; for (RKTableSection *section in self.sections) { NSUInteger rowIndex = 0; @@ -469,40 +513,45 @@ - (NSIndexPath *)indexPathForObject:(id)object { if ([rowObject isEqual:object]) { return [NSIndexPath indexPathForRow:rowIndex inSection:sectionIndex]; } - + rowIndex++; } sectionIndex++; } - + return nil; } -- (CGFloat)tableView:(UITableView *)theTableView heightForHeaderInSection:(NSInteger)sectionIndex { +- (CGFloat)tableView:(UITableView *)theTableView heightForHeaderInSection:(NSInteger)sectionIndex +{ NSAssert(theTableView == self.tableView, @"heightForHeaderInSection: invoked with inappropriate tableView: %@", theTableView); RKTableSection *section = [self sectionAtIndex:sectionIndex]; return section.headerHeight; } -- (CGFloat)tableView:(UITableView *)theTableView heightForFooterInSection:(NSInteger)sectionIndex { +- (CGFloat)tableView:(UITableView *)theTableView heightForFooterInSection:(NSInteger)sectionIndex +{ NSAssert(theTableView == self.tableView, @"heightForFooterInSection: invoked with inappropriate tableView: %@", theTableView); RKTableSection *section = [self sectionAtIndex:sectionIndex]; return section.footerHeight; } -- (UIView *)tableView:(UITableView *)theTableView viewForHeaderInSection:(NSInteger)sectionIndex { +- (UIView *)tableView:(UITableView *)theTableView viewForHeaderInSection:(NSInteger)sectionIndex +{ NSAssert(theTableView == self.tableView, @"viewForHeaderInSection: invoked with inappropriate tableView: %@", theTableView); RKTableSection *section = [self sectionAtIndex:sectionIndex]; return section.headerView; } -- (UIView *)tableView:(UITableView *)theTableView viewForFooterInSection:(NSInteger)sectionIndex { +- (UIView *)tableView:(UITableView *)theTableView viewForFooterInSection:(NSInteger)sectionIndex +{ NSAssert(theTableView == self.tableView, @"viewForFooterInSection: invoked with inappropriate tableView: %@", theTableView); RKTableSection *section = [self sectionAtIndex:sectionIndex]; return section.footerView; } -- (BOOL)isConsideredEmpty { +- (BOOL)isConsideredEmpty +{ NSUInteger nonRowItemsCount = [self.headerItems count] + [self.footerItems count]; nonRowItemsCount += self.emptyItem ? 1 : 0; BOOL isEmpty = (self.rowCount - nonRowItemsCount) == 0; diff --git a/Code/UI/RKTableItem.h b/Code/UI/RKTableItem.h index 7800d2ac07..11df234c1b 100644 --- a/Code/UI/RKTableItem.h +++ b/Code/UI/RKTableItem.h @@ -88,7 +88,7 @@ Return a new array of RKTableItem instances given a nil terminated list of strings. Each table item will have the text property set to the string provided. */ -+ (NSArray*)tableItemsFromStrings:(NSString *)firstString, ... NS_REQUIRES_NIL_TERMINATION; ++ (NSArray *)tableItemsFromStrings:(NSString *)firstString, ... NS_REQUIRES_NIL_TERMINATION; /** Returns a new table item @@ -122,7 +122,7 @@ For example: - NSArray* tableItems = [NSArray arrayWithObjects:[MyTableItem tableItemWithText:@"Foo" + NSArray *tableItems = [NSArray arrayWithObjects:[MyTableItem tableItemWithText:@"Foo" usingBlock:^(RKTableItem *tableItem) { [(MyTableItem *)tableItem setURL:@"app://whatever"]; }], ...]; diff --git a/Code/UI/RKTableItem.m b/Code/UI/RKTableItem.m index 63ed6f2591..8d130e94d8 100644 --- a/Code/UI/RKTableItem.m +++ b/Code/UI/RKTableItem.m @@ -30,12 +30,13 @@ @implementation RKTableItem @synthesize URL = _URL; @synthesize userData = _userData; -+ (NSArray*)tableItemsFromStrings:(NSString*)firstString, ... { ++ (NSArray *)tableItemsFromStrings:(NSString *)firstString, ... +{ va_list args; va_start(args, firstString); - NSMutableArray* tableItems = [NSMutableArray array]; - for (NSString* string = firstString; string != nil; string = va_arg(args, NSString*)) { - RKTableItem* tableItem = [RKTableItem new]; + NSMutableArray *tableItems = [NSMutableArray array]; + for (NSString *string = firstString; string != nil; string = va_arg(args, NSString *)) { + RKTableItem *tableItem = [RKTableItem new]; tableItem.text = string; [tableItems addObject:tableItem]; [tableItem release]; @@ -45,31 +46,36 @@ + (NSArray*)tableItemsFromStrings:(NSString*)firstString, ... { return [NSArray arrayWithArray:tableItems]; } -+ (id)tableItem { ++ (id)tableItem +{ return [[self new] autorelease]; } -+ (id)tableItemUsingBlock:(void (^)(RKTableItem *))block { - RKTableItem* tableItem = [self tableItem]; ++ (id)tableItemUsingBlock:(void (^)(RKTableItem *))block +{ + RKTableItem *tableItem = [self tableItem]; block(tableItem); return tableItem; } -+ (id)tableItemWithText:(NSString *)text { ++ (id)tableItemWithText:(NSString *)text +{ return [self tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = text; }]; } -+ (id)tableItemWithText:(NSString *)text detailText:(NSString *)detailText { ++ (id)tableItemWithText:(NSString *)text detailText:(NSString *)detailText +{ return [self tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = text; tableItem.detailText = detailText; }]; } -+ (id)tableItemWithText:(NSString *)text detailText:(NSString *)detailText image:(UIImage*)image { - RKTableItem* tableItem = [self new]; ++ (id)tableItemWithText:(NSString *)text detailText:(NSString *)detailText image:(UIImage *)image +{ + RKTableItem *tableItem = [self new]; tableItem.text = text; tableItem.detailText = detailText; tableItem.image = image; @@ -77,28 +83,32 @@ + (id)tableItemWithText:(NSString *)text detailText:(NSString *)detailText image return [tableItem autorelease]; } -+ (id)tableItemWithText:(NSString *)text usingBlock:(void (^)(RKTableItem *))block { - RKTableItem* tableItem = [[self new] autorelease]; ++ (id)tableItemWithText:(NSString *)text usingBlock:(void (^)(RKTableItem *))block +{ + RKTableItem *tableItem = [[self new] autorelease]; tableItem.text = text; block(tableItem); return tableItem; } -+ (id)tableItemWithText:(NSString *)text URL:(NSString *)URL { - RKTableItem* tableItem = [self tableItem]; ++ (id)tableItemWithText:(NSString *)text URL:(NSString *)URL +{ + RKTableItem *tableItem = [self tableItem]; tableItem.text = text; tableItem.URL = URL; return tableItem; } -+ (id)tableItemWithCellMapping:(RKTableViewCellMapping *)cellMapping { ++ (id)tableItemWithCellMapping:(RKTableViewCellMapping *)cellMapping +{ RKTableItem *tableItem = [self tableItem]; tableItem.cellMapping = cellMapping; return tableItem; } -+ (id)tableItemWithCellClass:(Class)tableViewCellSubclass { ++ (id)tableItemWithCellClass:(Class)tableViewCellSubclass +{ RKTableItem *tableItem = [self tableItem]; tableItem.cellMapping = [RKTableViewCellMapping cellMapping]; tableItem.cellMapping.cellClass = tableViewCellSubclass; @@ -106,7 +116,8 @@ + (id)tableItemWithCellClass:(Class)tableViewCellSubclass { return tableItem; } -- (id)init { +- (id)init +{ self = [super init]; if (self) { _userData = [RKMutableBlockDictionary new]; @@ -116,7 +127,8 @@ - (id)init { return self; } -- (void)dealloc { +- (void)dealloc +{ [_text release]; [_detailText release]; [_image release]; @@ -126,17 +138,20 @@ - (void)dealloc { [super dealloc]; } -- (NSString*)description { +- (NSString *)description +{ return [NSString stringWithFormat:@"<%@: %p text=%@, detailText=%@, image=%p>", NSStringFromClass([self class]), self, self.text, self.detailText, self.image]; } #pragma mark - User Data KVC Proxy -- (void)setValue:(id)value forUndefinedKey:(NSString *)key { +- (void)setValue:(id)value forUndefinedKey:(NSString *)key +{ [self.userData setValue:value ? value : [NSNull null] forKey:key]; } -- (id)valueForUndefinedKey:(NSString *)key { +- (id)valueForUndefinedKey:(NSString *)key +{ return [self.userData valueForKey:key]; } diff --git a/Code/UI/RKTableSection.h b/Code/UI/RKTableSection.h index 86ec5bf6a7..48cc31bf11 100644 --- a/Code/UI/RKTableSection.h +++ b/Code/UI/RKTableSection.h @@ -24,33 +24,30 @@ @class RKTableController; -@interface RKTableSection : NSObject { - @protected - NSMutableArray *_objects; -} +@interface RKTableSection : NSObject // Basics -@property (nonatomic, assign) RKTableController* tableController; -@property (nonatomic, readonly) UITableView* tableView; +@property (nonatomic, assign) RKTableController *tableController; +@property (nonatomic, readonly) UITableView *tableView; // Object Mapping Table Stuff -@property (nonatomic, retain) NSArray* objects; -@property (nonatomic, retain) RKTableViewCellMappings* cellMappings; +@property (nonatomic, retain) NSArray *objects; +@property (nonatomic, retain) RKTableViewCellMappings *cellMappings; // Header & Footer Views, etc. -@property (nonatomic, retain) NSString* headerTitle; -@property (nonatomic, retain) NSString* footerTitle; +@property (nonatomic, retain) NSString *headerTitle; +@property (nonatomic, retain) NSString *footerTitle; @property (nonatomic, assign) CGFloat headerHeight; @property (nonatomic, assign) CGFloat footerHeight; -@property (nonatomic, retain) UIView* headerView; -@property (nonatomic, retain) UIView* footerView; +@property (nonatomic, retain) UIView *headerView; +@property (nonatomic, retain) UIView *footerView; // number of cells in the section @property (nonatomic, readonly) NSUInteger rowCount; + (id)section; + (id)sectionUsingBlock:(void (^)(RKTableSection *))block; -+ (id)sectionForObjects:(NSArray*)objects withMappings:(RKTableViewCellMappings*)cellMappings; ++ (id)sectionForObjects:(NSArray *)objects withMappings:(RKTableViewCellMappings *)cellMappings; - (id)objectAtIndex:(NSUInteger)rowIndex; - (void)insertObject:(id)object atIndex:(NSUInteger)index; diff --git a/Code/UI/RKTableSection.m b/Code/UI/RKTableSection.m index 73f9627c74..7e8c9066cd 100644 --- a/Code/UI/RKTableSection.m +++ b/Code/UI/RKTableSection.m @@ -39,24 +39,28 @@ @implementation RKTableSection @synthesize headerView = _headerView; @synthesize footerView = _footerView; -+ (id)section { ++ (id)section +{ return [[self new] autorelease]; } -+ (id)sectionUsingBlock:(void (^)(RKTableSection *))block { - RKTableSection* section = [self section]; ++ (id)sectionUsingBlock:(void (^)(RKTableSection *))block +{ + RKTableSection *section = [self section]; block(section); return section; } -+ (id)sectionForObjects:(NSArray *)objects withMappings:(RKTableViewCellMappings *)cellMappings { ++ (id)sectionForObjects:(NSArray *)objects withMappings:(RKTableViewCellMappings *)cellMappings +{ return [self sectionUsingBlock:^(RKTableSection *section) { section.objects = objects; section.cellMappings = cellMappings; }]; } -- (id)init { +- (id)init +{ self = [super init]; if (self) { _objects = [NSMutableArray new]; @@ -67,7 +71,8 @@ - (id)init { return self; } -- (void)dealloc { +- (void)dealloc +{ [_objects release]; [_cellMappings release]; [_headerTitle release]; @@ -77,34 +82,39 @@ - (void)dealloc { [super dealloc]; } -- (void)setObjects:(NSArray *)objects { +- (void)setObjects:(NSArray *)objects +{ if (! [objects isMemberOfClass:[NSMutableArray class]]) { - NSMutableArray* mutableObjects = [objects mutableCopy]; + NSMutableArray *mutableObjects = [objects mutableCopy]; [_objects release]; _objects = mutableObjects; } else { [objects retain]; [_objects release]; - _objects = (NSMutableArray *) objects; + _objects = (NSMutableArray *)objects; } } -- (NSUInteger)rowCount { +- (NSUInteger)rowCount +{ return [_objects count]; } -- (id)objectAtIndex:(NSUInteger)rowIndex { +- (id)objectAtIndex:(NSUInteger)rowIndex +{ return [_objects objectAtIndex:rowIndex]; } -- (UITableView*)tableView { +- (UITableView *)tableView +{ return _tableController.tableView; } -- (void)insertObject:(id)object atIndex:(NSUInteger)index { - [(NSMutableArray*)_objects insertObject:object atIndex:index]; +- (void)insertObject:(id)object atIndex:(NSUInteger)index +{ + [(NSMutableArray *)_objects insertObject:object atIndex:index]; - NSIndexPath* indexPath = [NSIndexPath indexPathForRow:index + NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:[_tableController indexForSection:self]]; [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:_tableController.defaultRowAnimation]; @@ -114,11 +124,12 @@ - (void)insertObject:(id)object atIndex:(NSUInteger)index { } } -- (void)removeObjectAtIndex:(NSUInteger)index { +- (void)removeObjectAtIndex:(NSUInteger)index +{ id object = [self objectAtIndex:index]; - [(NSMutableArray*)_objects removeObjectAtIndex:index]; + [(NSMutableArray *)_objects removeObjectAtIndex:index]; - NSIndexPath* indexPath = [NSIndexPath indexPathForRow:index + NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:[_tableController indexForSection:self]]; [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:_tableController.defaultRowAnimation]; @@ -128,10 +139,11 @@ - (void)removeObjectAtIndex:(NSUInteger)index { } } -- (void)replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { - [(NSMutableArray*)_objects replaceObjectAtIndex:index withObject:object]; +- (void)replaceObjectAtIndex:(NSUInteger)index withObject:(id)object +{ + [(NSMutableArray *)_objects replaceObjectAtIndex:index withObject:object]; - NSIndexPath* indexPath = [NSIndexPath indexPathForRow:index + NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:[_tableController indexForSection:self]]; [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:_tableController.defaultRowAnimation]; @@ -141,7 +153,8 @@ - (void)replaceObjectAtIndex:(NSUInteger)index withObject:(id)object { } } -- (void)moveObjectAtIndex:(NSUInteger)sourceIndex toIndex:(NSUInteger)destinationIndex { +- (void)moveObjectAtIndex:(NSUInteger)sourceIndex toIndex:(NSUInteger)destinationIndex +{ [self.tableView beginUpdates]; id object = [[self objectAtIndex:sourceIndex] retain]; [self removeObjectAtIndex:sourceIndex]; diff --git a/Code/UI/RKTableViewCellMapping.h b/Code/UI/RKTableViewCellMapping.h index 573d08239f..b61780ca11 100644 --- a/Code/UI/RKTableViewCellMapping.h +++ b/Code/UI/RKTableViewCellMapping.h @@ -26,9 +26,9 @@ typedef void(^RKTableViewCellForObjectAtIndexPathBlock)(UITableViewCell *cell, id object, NSIndexPath *indexPath); typedef CGFloat(^RKTableViewHeightOfCellForObjectAtIndexPathBlock)(id object, NSIndexPath *indexPath); typedef void(^RKTableViewAccessoryButtonTappedForObjectAtIndexPathBlock)(UITableViewCell *cell, id object, NSIndexPath *indexPath); -typedef NSString*(^RKTableViewTitleForDeleteButtonForObjectAtIndexPathBlock)(UITableViewCell *cell, id object, NSIndexPath *indexPath); +typedef NSString *(^RKTableViewTitleForDeleteButtonForObjectAtIndexPathBlock)(UITableViewCell *cell, id object, NSIndexPath *indexPath); typedef UITableViewCellEditingStyle(^RKTableViewEditingStyleForObjectAtIndexPathBlock)(UITableViewCell *cell, id object, NSIndexPath *indexPath); -typedef NSIndexPath*(^RKTableViewTargetIndexPathForMoveBlock)(UITableViewCell *cell, id object, NSIndexPath *sourceIndexPath, NSIndexPath *destIndexPath); +typedef NSIndexPath *(^RKTableViewTargetIndexPathForMoveBlock)(UITableViewCell *cell, id object, NSIndexPath *sourceIndexPath, NSIndexPath *destIndexPath); typedef void(^RKTableViewAnonymousBlock)(); typedef void(^RKTableViewCellBlock)(UITableViewCell *cell); @@ -69,7 +69,7 @@ typedef void(^RKTableViewCellBlock)(UITableViewCell *cell); @default @"GGImageButtonTableViewCell" @see cellClass */ -@property (nonatomic, assign) NSString* cellClassName; +@property (nonatomic, assign) NSString *cellClassName; /** A reuse identifier for cells created using this mapping. These cells will be @@ -80,7 +80,7 @@ typedef void(^RKTableViewCellBlock)(UITableViewCell *cell); @default NSStringFromClass(self.objectClass) */ -@property (nonatomic, retain) NSString* reuseIdentifier; +@property (nonatomic, retain) NSString *reuseIdentifier; /** A Boolean value that determines whether the cell mapping manages basic cell diff --git a/Code/UI/RKTableViewCellMapping.m b/Code/UI/RKTableViewCellMapping.m index dd579c4162..f83159880b 100644 --- a/Code/UI/RKTableViewCellMapping.m +++ b/Code/UI/RKTableViewCellMapping.m @@ -49,11 +49,13 @@ - (void)actionForControlEvent:(id)sender; @implementation RKControlBlockAction -+ (id)actionWithBlock:(void(^)(id sender))block { ++ (id)actionWithBlock:(void(^)(id sender))block +{ return [[[self alloc] initWithBlock:block] autorelease]; } -- (id)initWithBlock:(void(^)(id sender))block { +- (id)initWithBlock:(void(^)(id sender))block +{ self = [self init]; if (self) { _actionBlock = Block_copy(block); @@ -62,15 +64,18 @@ - (id)initWithBlock:(void(^)(id sender))block { return self; } -- (void)actionForControlEvent:(id)sender { +- (void)actionForControlEvent:(id)sender +{ _actionBlock(sender); } -- (SEL)actionSelector { +- (SEL)actionSelector +{ return @selector(actionForControlEvent:); } -- (void)dealloc { +- (void)dealloc +{ Block_release(_actionBlock); [super dealloc]; } @@ -95,29 +100,34 @@ @implementation RKTableViewCellMapping @synthesize deselectsRowOnSelection = _deselectsRowOnSelection; @synthesize managesCellAttributes; -+ (id)cellMapping { ++ (id)cellMapping +{ return [self mappingForClass:[UITableViewCell class]]; } -+ (id)cellMappingForReuseIdentifier:(NSString *)reuseIdentifier { ++ (id)cellMappingForReuseIdentifier:(NSString *)reuseIdentifier +{ RKTableViewCellMapping *cellMapping = [self cellMapping]; cellMapping.reuseIdentifier = reuseIdentifier; return cellMapping; } -+ (id)defaultCellMapping { ++ (id)defaultCellMapping +{ RKTableViewCellMapping *cellMapping = [self cellMapping]; [cellMapping addDefaultMappings]; return cellMapping; } -+ (id)cellMappingUsingBlock:(void (^)(RKTableViewCellMapping*))block { - RKTableViewCellMapping* cellMapping = [self cellMapping]; ++ (id)cellMappingUsingBlock:(void (^)(RKTableViewCellMapping *))block +{ + RKTableViewCellMapping *cellMapping = [self cellMapping]; block(cellMapping); return cellMapping; } -- (id)init { +- (id)init +{ self = [super init]; if (self) { self.cellClass = [UITableViewCell class]; @@ -133,13 +143,15 @@ - (id)init { return self; } -- (void)addDefaultMappings { +- (void)addDefaultMappings +{ [self mapKeyPath:@"text" toAttribute:@"textLabel.text"]; [self mapKeyPath:@"detailText" toAttribute:@"detailTextLabel.text"]; [self mapKeyPath:@"image" toAttribute:@"imageView.image"]; } -- (void)dealloc { +- (void)dealloc +{ [_reuseIdentifier release]; [_prepareCellBlocks release]; Block_release(_onSelectCell); @@ -153,11 +165,13 @@ - (void)dealloc { [super dealloc]; } -- (NSMutableArray *)prepareCellBlocks { +- (NSMutableArray *)prepareCellBlocks +{ return _prepareCellBlocks; } -- (id)copyWithZone:(NSZone *)zone { +- (id)copyWithZone:(NSZone *)zone +{ RKTableViewCellMapping *copy = [super copyWithZone:zone]; copy.reuseIdentifier = self.reuseIdentifier; copy.style = self.style; @@ -185,10 +199,11 @@ - (id)copyWithZone:(NSZone *)zone { } -- (id)mappableObjectForData:(UITableView *)tableView { +- (id)mappableObjectForData:(UITableView *)tableView +{ NSAssert([tableView isKindOfClass:[UITableView class]], @"Expected to be invoked with a tableView as the data. Got %@", tableView); RKLogTrace(@"About to dequeue reusable cell using self.reuseIdentifier=%@", self.reuseIdentifier); - UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:self.reuseIdentifier]; + UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:self.reuseIdentifier]; if (! cell) { cell = [[[self.objectClass alloc] initWithStyle:self.style reuseIdentifier:self.reuseIdentifier] autorelease]; @@ -207,50 +222,60 @@ - (id)mappableObjectForData:(UITableView *)tableView { return cell; } -- (void)setSelectionStyle:(UITableViewCellSelectionStyle)selectionStyle { +- (void)setSelectionStyle:(UITableViewCellSelectionStyle)selectionStyle +{ self.managesCellAttributes = YES; _selectionStyle = selectionStyle; } -- (void)setAccessoryType:(UITableViewCellAccessoryType)accessoryType { +- (void)setAccessoryType:(UITableViewCellAccessoryType)accessoryType +{ self.managesCellAttributes = YES; _accessoryType = accessoryType; } -- (void)setObjectClass:(Class)objectClass { +- (void)setObjectClass:(Class)objectClass +{ NSAssert([objectClass isSubclassOfClass:[UITableViewCell class]], @"Cell mappings can only target classes that inherit from UITableViewCell"); [super setObjectClass:objectClass]; } -- (void)setCellClass:(Class)cellClass { +- (void)setCellClass:(Class)cellClass +{ [self setObjectClass:cellClass]; } -- (NSString*)cellClassName { +- (NSString *)cellClassName +{ return NSStringFromClass(self.cellClass); } -- (void)setCellClassName:(NSString *)cellClassName { +- (void)setCellClassName:(NSString *)cellClassName +{ self.cellClass = NSClassFromString(cellClassName); } -- (Class)cellClass { +- (Class)cellClass +{ return [self objectClass]; } -- (NSString *)reuseIdentifier { +- (NSString *)reuseIdentifier +{ return _reuseIdentifier ? _reuseIdentifier : NSStringFromClass(self.objectClass); } #pragma mark - Control Action Helpers -- (void)addPrepareCellBlock:(void (^)(UITableViewCell *cell))block { +- (void)addPrepareCellBlock:(void (^)(UITableViewCell *cell))block +{ void (^blockCopy)(UITableViewCell *cell) = [block copy]; [_prepareCellBlocks addObject:blockCopy]; [blockCopy release]; } -- (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents toControlAtKeyPath:(NSString *)keyPath { +- (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents toControlAtKeyPath:(NSString *)keyPath +{ [self addPrepareCellBlock:^(UITableViewCell *cell) { UIControl *control = [cell valueForKeyPath:keyPath]; if (control) { @@ -261,11 +286,13 @@ - (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvent }]; } -- (void)addTarget:(id)target action:(SEL)action forTouchEventToControlAtKeyPath:(NSString *)keyPath { +- (void)addTarget:(id)target action:(SEL)action forTouchEventToControlAtKeyPath:(NSString *)keyPath +{ [self addTarget:target action:action forControlEvents:UIControlEventTouchUpInside toControlAtKeyPath:keyPath]; } -- (void)addBlockAction:(void (^)(id sender))block forControlEvents:(UIControlEvents)controlEvents toControlAtKeyPath:(NSString *)keyPath { +- (void)addBlockAction:(void (^)(id sender))block forControlEvents:(UIControlEvents)controlEvents toControlAtKeyPath:(NSString *)keyPath +{ [self addPrepareCellBlock:^(UITableViewCell *cell) { RKControlBlockAction *blockAction = [RKControlBlockAction actionWithBlock:block]; UIControl *control = [cell valueForKeyPath:keyPath]; @@ -277,7 +304,8 @@ - (void)addBlockAction:(void (^)(id sender))block forControlEvents:(UIControlEve }]; } -- (void)addBlockAction:(void (^)(id sender))block forTouchEventToControlAtKeyPath:(NSString *)keyPath { +- (void)addBlockAction:(void (^)(id sender))block forTouchEventToControlAtKeyPath:(NSString *)keyPath +{ [self addBlockAction:block forControlEvents:UIControlEventTouchUpInside toControlAtKeyPath:keyPath]; } diff --git a/Code/UI/RKTableViewCellMappings.h b/Code/UI/RKTableViewCellMappings.h index 2426943a77..6060d05540 100644 --- a/Code/UI/RKTableViewCellMappings.h +++ b/Code/UI/RKTableViewCellMappings.h @@ -22,12 +22,12 @@ @interface RKTableViewCellMappings : NSObject { @private - NSMutableDictionary* _cellMappings; + NSMutableDictionary *_cellMappings; } + (id)cellMappings; -- (void)setCellMapping:(RKTableViewCellMapping*)cellMapping forClass:(Class)objectClass; -- (RKTableViewCellMapping*)cellMappingForClass:(Class)objectClass; -- (RKTableViewCellMapping*)cellMappingForObject:(id)object; +- (void)setCellMapping:(RKTableViewCellMapping *)cellMapping forClass:(Class)objectClass; +- (RKTableViewCellMapping *)cellMappingForClass:(Class)objectClass; +- (RKTableViewCellMapping *)cellMappingForObject:(id)object; @end diff --git a/Code/UI/RKTableViewCellMappings.m b/Code/UI/RKTableViewCellMappings.m index a7ddbde93c..86caa707fd 100644 --- a/Code/UI/RKTableViewCellMappings.m +++ b/Code/UI/RKTableViewCellMappings.m @@ -22,11 +22,13 @@ @implementation RKTableViewCellMappings -+ (id)cellMappings { ++ (id)cellMappings +{ return [[self new] autorelease]; } -- (id)init { +- (id)init +{ self = [super init]; if (self) { _cellMappings = [NSMutableDictionary new]; @@ -35,7 +37,8 @@ - (id)init { return self; } -- (void)setCellMapping:(RKTableViewCellMapping*)cellMapping forClass:(Class)objectClass { +- (void)setCellMapping:(RKTableViewCellMapping *)cellMapping forClass:(Class)objectClass +{ if ([_cellMappings objectForKey:objectClass]) { @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"A tableViewCell mapping has already been registered for objects of type '%@'", NSStringFromClass(objectClass)] @@ -45,9 +48,10 @@ - (void)setCellMapping:(RKTableViewCellMapping*)cellMapping forClass:(Class)obje [_cellMappings setObject:cellMapping forKey:objectClass]; } -- (RKTableViewCellMapping*)cellMappingForClass:(Class)objectClass { +- (RKTableViewCellMapping *)cellMappingForClass:(Class)objectClass +{ // Exact match - RKTableViewCellMapping* cellMapping = [_cellMappings objectForKey:objectClass]; + RKTableViewCellMapping *cellMapping = [_cellMappings objectForKey:objectClass]; if (cellMapping) return cellMapping; // Subclass match @@ -60,11 +64,12 @@ - (RKTableViewCellMapping*)cellMappingForClass:(Class)objectClass { return nil; } -- (RKTableViewCellMapping*)cellMappingForObject:(id)object { +- (RKTableViewCellMapping *)cellMappingForObject:(id)object +{ if ([object respondsToSelector:@selector(cellMapping)]) { // TODO: Trace logging... // TODO: This needs unit test coverage on the did select row case... - RKTableViewCellMapping* cellMapping = [object cellMapping]; + RKTableViewCellMapping *cellMapping = [object cellMapping]; if (cellMapping) return [object cellMapping]; } diff --git a/Code/UI/UIImage+RKAdditions.m b/Code/UI/UIImage+RKAdditions.m index ef894d6a4c..fe6a8b00e4 100644 --- a/Code/UI/UIImage+RKAdditions.m +++ b/Code/UI/UIImage+RKAdditions.m @@ -12,14 +12,15 @@ @implementation UIImage (RKAdditions) -- (id)initWithContentsOfResolutionIndependentFile:(NSString *)path { - if ( [[[UIDevice currentDevice] systemVersion] intValue] >= 4 && [[UIScreen mainScreen] scale] == 2.0 ) { +- (id)initWithContentsOfResolutionIndependentFile:(NSString *)path +{ + if ([[[UIDevice currentDevice] systemVersion] intValue] >= 4 && [[UIScreen mainScreen] scale] == 2.0) { NSString *path2x = [[path stringByDeletingLastPathComponent] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@@2x.%@", [[path lastPathComponent] stringByDeletingPathExtension], [path pathExtension]]]; - if ( [[NSFileManager defaultManager] fileExistsAtPath:path2x] ) { + if ([[NSFileManager defaultManager] fileExistsAtPath:path2x]) { return [self initWithCGImage:[[UIImage imageWithData:[NSData dataWithContentsOfFile:path2x]] CGImage] scale:2.0 orientation:UIImageOrientationUp]; } } @@ -27,7 +28,8 @@ - (id)initWithContentsOfResolutionIndependentFile:(NSString *)path { return [self initWithData:[NSData dataWithContentsOfFile:path]]; } -+ (UIImage *)imageWithContentsOfResolutionIndependentFile:(NSString *)path { ++ (UIImage *)imageWithContentsOfResolutionIndependentFile:(NSString *)path +{ return [[[UIImage alloc] initWithContentsOfResolutionIndependentFile:path] autorelease]; } diff --git a/Code/UI/UIView+FindFirstResponder.h b/Code/UI/UIView+FindFirstResponder.h index e57fad3d7d..882847abc4 100644 --- a/Code/UI/UIView+FindFirstResponder.h +++ b/Code/UI/UIView+FindFirstResponder.h @@ -22,6 +22,6 @@ @interface UIView (FindFirstResponder) -- (UIView*)findFirstResponder; +- (UIView *)findFirstResponder; @end diff --git a/Code/UI/UIView+FindFirstResponder.m b/Code/UI/UIView+FindFirstResponder.m index 512b4e6975..c76aa2a00c 100644 --- a/Code/UI/UIView+FindFirstResponder.m +++ b/Code/UI/UIView+FindFirstResponder.m @@ -23,13 +23,14 @@ @implementation UIView (FindFirstResponder) -- (UIView*)findFirstResponder { +- (UIView *)findFirstResponder +{ if (self.isFirstResponder) { return self; } - for (UIView* subView in self.subviews) { - UIView* firstResponder = [subView findFirstResponder]; + for (UIView *subView in self.subviews) { + UIView *firstResponder = [subView findFirstResponder]; if (firstResponder != nil) { return firstResponder; } diff --git a/Docs/Object Mapping.md b/Docs/Object Mapping.md index 333bd29382..a67fca302d 100644 --- a/Docs/Object Mapping.md +++ b/Docs/Object Mapping.md @@ -609,12 +609,12 @@ Thus far we have examined clear-cut cases where the appropriate object mapping c key path or by the developer directly providing the mapping. Sometimes it is desirable to dynamically determine the appropriate object mapping to use at mapping time. Perhaps we have a collection of objects with identical attribute names, but we wish to represent them differently. Or maybe we are loading a collection of objects that are not KVC compliant, but contain a mixture -of types that we would like to model. RestKit supports such use cases via the RKObjectDynamicMapping class. -RKObjectDynamicMapping is a sibling class to RKObjectMapping and can be added to instances of RKObjectMappingProvider and -used to configure RKObjectMappingOperation instances. RKObjectDynamicMapping allows you to hook into the mapping process +of types that we would like to model. RestKit supports such use cases via the RKDynamicObjectMapping class. +RKDynamicObjectMapping is a sibling class to RKObjectMapping and can be added to instances of RKObjectMappingProvider and +used to configure RKObjectMappingOperation instances. RKDynamicObjectMapping allows you to hook into the mapping process and determine an appropriate RKObjectMapping to use on a per-object basis. -When RestKit is performing a mapping operation and the current mapping being applied is an RKObjectDynamicMapping instance, +When RestKit is performing a mapping operation and the current mapping being applied is an RKDynamicObjectMapping instance, the dynamic mapping will be sent the `objectMappingForDictionary:` message with the NSDictionary that is currently being mapped. The dynamic mapping is responsible for introspecting the contents of the dictionary and returning an RKObjectMapping instance that can be used to map the data into a concrete object. @@ -625,9 +625,9 @@ There are three ways in which the determination of the appropriate object mappin be used to infer the appropriate object type, then you are in luck -- RestKit can handle the dynamic mapping via simple configuration. 2. Via a delegate callback. If your data requires some special analysis or you want to dynamically construct an object mapping -to handle the data, you can assign a delegate to the RKObjectDynamicMapping and you will be called back to perform whatever +to handle the data, you can assign a delegate to the RKDynamicObjectMapping and you will be called back to perform whatever logic you need to implement the object mapping lookup/construction. -3. Via a delegate block invocation. Similar to the delegate configuration, you can assign a delegateBlock to the RKObjectDynamicMapping that will be invoked to determine the appropriate RKObjectMapping to use for the mappable data. +3. Via a delegate block invocation. Similar to the delegate configuration, you can assign a delegateBlock to the RKDynamicObjectMapping that will be invoked to determine the appropriate RKObjectMapping to use for the mappable data. To illustrate these concepts, let's consider the following JSON fragment: @@ -667,7 +667,7 @@ RKObjectMapping* boyMapping = [RKObjectMapping mappingForClass:[Boy class]]; [boyMapping mapAttributes:@"name", nil]; RKObjectMapping* girlMapping = [RKObjectMapping mappingForClass:[Girl class]]; [girlMapping mapAttributes:@"name", nil]; -RKObjectDynamicMapping* dynamicMapping = [RKObjectDynamicMapping dynamicMapping]; +RKDynamicObjectMapping* dynamicMapping = [RKDynamicObjectMapping dynamicMapping]; [boyMapping mapKeyPath:@"friends" toRelationship:@"friends" withMapping:dynamicMapping]; [girlMapping mapKeyPath:@"friends" toRelationship:@"friends" withMapping:dynamicMapping]; diff --git a/Examples/RKCatalog/App/RKCatalog.h b/Examples/RKCatalog/App/RKCatalog.h index 4ff4ec98c4..d6c97904fb 100644 --- a/Examples/RKCatalog/App/RKCatalog.h +++ b/Examples/RKCatalog/App/RKCatalog.h @@ -11,4 +11,4 @@ #import // Import the base URL defined in the app delegate -extern NSURL* gRKCatalogBaseURL; +extern NSURL *gRKCatalogBaseURL; diff --git a/Examples/RKCatalog/App/RKCatalogAppDelegate.m b/Examples/RKCatalog/App/RKCatalogAppDelegate.m index 2a327342e0..4e9708ca43 100644 --- a/Examples/RKCatalog/App/RKCatalogAppDelegate.m +++ b/Examples/RKCatalog/App/RKCatalogAppDelegate.m @@ -16,7 +16,8 @@ @implementation RKCatalogAppDelegate @synthesize window; @synthesize navigationController; -- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { +- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions +{ // Override point for customization after application launch. // Add the navigation controller's view to the window and display. self.window.rootViewController = self.navigationController; @@ -28,7 +29,8 @@ - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:( return YES; } -- (void)dealloc { +- (void)dealloc +{ [window release]; [navigationController release]; [super dealloc]; diff --git a/Examples/RKCatalog/App/RootViewController.h b/Examples/RKCatalog/App/RootViewController.h index 598af3bfde..e19e249552 100644 --- a/Examples/RKCatalog/App/RootViewController.h +++ b/Examples/RKCatalog/App/RootViewController.h @@ -9,7 +9,7 @@ #import @interface RootViewController : UITableViewController { - NSArray* _exampleTableItems; + NSArray *_exampleTableItems; } @end diff --git a/Examples/RKCatalog/App/RootViewController.m b/Examples/RKCatalog/App/RootViewController.m index 33ee604f67..df8175628b 100644 --- a/Examples/RKCatalog/App/RootViewController.m +++ b/Examples/RKCatalog/App/RootViewController.m @@ -11,7 +11,8 @@ @implementation RootViewController -- (void)viewDidLoad { +- (void)viewDidLoad +{ [super viewDidLoad]; _exampleTableItems = [[NSArray alloc] initWithObjects: @@ -26,21 +27,25 @@ - (void)viewDidLoad { nil]; } -- (void)dealloc { +- (void)dealloc +{ [_exampleTableItems release]; [super dealloc]; } -- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { +- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView +{ return 1; } -- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { +- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section +{ return [_exampleTableItems count]; } -- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { +- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath +{ static NSString *cellIdentifier = @"RKCatalogCellIdentifier"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; @@ -50,20 +55,21 @@ - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(N cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; } - NSString* exampleName = [_exampleTableItems objectAtIndex:indexPath.row]; + NSString *exampleName = [_exampleTableItems objectAtIndex:indexPath.row]; cell.textLabel.text = exampleName; return cell; } -- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { +- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath +{ // Clear the singleton instances to isolate the examples [RKClient setSharedClient:nil]; [RKObjectManager setSharedManager:nil]; - NSString* exampleName = [_exampleTableItems objectAtIndex:indexPath.row]; + NSString *exampleName = [_exampleTableItems objectAtIndex:indexPath.row]; Class exampleClass = NSClassFromString(exampleName); - UIViewController* exampleController = [[exampleClass alloc] initWithNibName:exampleName bundle:nil]; + UIViewController *exampleController = [[exampleClass alloc] initWithNibName:exampleName bundle:nil]; if (exampleController) { [self.navigationController pushViewController:exampleController animated:YES]; if (exampleController.title == nil) { diff --git a/Examples/RKCatalog/Examples/RKAuthenticationExample/RKAuthenticationExample.m b/Examples/RKCatalog/Examples/RKAuthenticationExample/RKAuthenticationExample.m index cde8d1a74d..f221cdc1cb 100644 --- a/Examples/RKCatalog/Examples/RKAuthenticationExample/RKAuthenticationExample.m +++ b/Examples/RKCatalog/Examples/RKAuthenticationExample/RKAuthenticationExample.m @@ -26,7 +26,8 @@ - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil return self; } -- (void)dealloc { +- (void)dealloc +{ [authenticatedRequest cancel]; [authenticatedRequest release]; authenticatedRequest = nil; @@ -39,7 +40,8 @@ - (void)dealloc { It is important to remember that RKClient is really just a factory object for instances of RKRequest. At any time you can directly configure an RKRequest instead. */ -- (void)sendRequest { +- (void)sendRequest +{ NSURL *URL = [NSURL URLWithString:[URLTextField text]]; RKRequest *newRequest = [RKRequest requestWithURL:URL]; newRequest.delegate = self; @@ -50,24 +52,28 @@ - (void)sendRequest { self.authenticatedRequest = newRequest; } -- (void)request:(RKRequest *)request didFailLoadWithError:(NSError *)error { +- (void)request:(RKRequest *)request didFailLoadWithError:(NSError *)error +{ RKLogError(@"Load of RKRequest %@ failed with error: %@", request, error); [request release]; } -- (void)request:(RKRequest *)request didLoadResponse:(RKResponse *)response { +- (void)request:(RKRequest *)request didLoadResponse:(RKResponse *)response +{ RKLogCritical(@"Loading of RKRequest %@ completed with status code %d. Response body: %@", request, response.statusCode, [response bodyAsString]); [request release]; } #pragma mark - UIPickerViewDataSource -- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView { +- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView +{ return 1; } // returns the # of rows in each component.. -- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component { +- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component +{ return 0; } diff --git a/Examples/RKCatalog/Examples/RKBackgroundRequestExample/RKBackgroundRequestExample.h b/Examples/RKCatalog/Examples/RKBackgroundRequestExample/RKBackgroundRequestExample.h index 79e6b768bc..e75f00f2c9 100644 --- a/Examples/RKCatalog/Examples/RKBackgroundRequestExample/RKBackgroundRequestExample.h +++ b/Examples/RKCatalog/Examples/RKBackgroundRequestExample/RKBackgroundRequestExample.h @@ -9,14 +9,14 @@ #import "RKCatalog.h" @interface RKBackgroundRequestExample : UIViewController { - UIButton* _sendButton; - UISegmentedControl* _segmentedControl; - UILabel* _statusLabel; + UIButton *_sendButton; + UISegmentedControl *_segmentedControl; + UILabel *_statusLabel; } -@property (nonatomic, retain) IBOutlet UIButton* sendButton; -@property (nonatomic, retain) IBOutlet UISegmentedControl* segmentedControl; -@property (nonatomic, retain) IBOutlet UILabel* statusLabel; +@property (nonatomic, retain) IBOutlet UIButton *sendButton; +@property (nonatomic, retain) IBOutlet UISegmentedControl *segmentedControl; +@property (nonatomic, retain) IBOutlet UILabel *statusLabel; - (IBAction)sendRequest; diff --git a/Examples/RKCatalog/Examples/RKBackgroundRequestExample/RKBackgroundRequestExample.m b/Examples/RKCatalog/Examples/RKBackgroundRequestExample/RKBackgroundRequestExample.m index 2c89b017e3..d85de4f2be 100644 --- a/Examples/RKCatalog/Examples/RKBackgroundRequestExample/RKBackgroundRequestExample.m +++ b/Examples/RKCatalog/Examples/RKBackgroundRequestExample/RKBackgroundRequestExample.m @@ -15,50 +15,58 @@ @implementation RKBackgroundRequestExample @synthesize segmentedControl = _segmentedControl; @synthesize statusLabel = _statusLabel; -- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { +- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil +{ self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { - RKClient* client = [RKClient clientWithBaseURL:gRKCatalogBaseURL]; + RKClient *client = [RKClient clientWithBaseURL:gRKCatalogBaseURL]; [RKClient setSharedClient:client]; } return self; } -- (void)dealloc { +- (void)dealloc +{ [[RKClient sharedClient].requestQueue cancelRequestsWithDelegate:self]; [super dealloc]; } -- (IBAction)sendRequest { - RKRequest* request = [[RKClient sharedClient] requestWithResourcePath:@"/RKBackgroundRequestExample"]; +- (IBAction)sendRequest +{ + RKRequest *request = [[RKClient sharedClient] requestWithResourcePath:@"/RKBackgroundRequestExample"]; request.delegate = self; request.backgroundPolicy = _segmentedControl.selectedSegmentIndex; [request send]; _sendButton.enabled = NO; } -- (void)requestDidStartLoad:(RKRequest *)request { +- (void)requestDidStartLoad:(RKRequest *)request +{ _statusLabel.text = [NSString stringWithFormat:@"Sent request with background policy %d at %@", request.backgroundPolicy, [NSDate date]]; } -- (void)requestDidTimeout:(RKRequest *)request { +- (void)requestDidTimeout:(RKRequest *)request +{ _statusLabel.text = @"Request timed out during background processing"; _sendButton.enabled = YES; } -- (void)requestDidCancelLoad:(RKRequest *)request { +- (void)requestDidCancelLoad:(RKRequest *)request +{ _statusLabel.text = @"Request canceled"; _sendButton.enabled = YES; } -- (void)request:(RKRequest *)request didLoadResponse:(RKResponse *)response { +- (void)request:(RKRequest *)request didLoadResponse:(RKResponse *)response +{ _statusLabel.text = [NSString stringWithFormat:@"Request completed with response: '%@'", [response bodyAsString]]; _sendButton.enabled = YES; } -- (void)request:(RKRequest *)request didFailLoadWithError:(NSError *)error { +- (void)request:(RKRequest *)request didFailLoadWithError:(NSError *)error +{ _statusLabel.text = [NSString stringWithFormat:@"Request failed with error: %@", [error localizedDescription]]; _sendButton.enabled = YES; } diff --git a/Examples/RKCatalog/Examples/RKCoreDataExample/RKCoreDataExample.h b/Examples/RKCatalog/Examples/RKCoreDataExample/RKCoreDataExample.h index 2520f42a96..8a5d3319df 100644 --- a/Examples/RKCatalog/Examples/RKCoreDataExample/RKCoreDataExample.h +++ b/Examples/RKCatalog/Examples/RKCoreDataExample/RKCoreDataExample.h @@ -9,8 +9,8 @@ #import "RKCatalog.h" @interface RKCoreDataExample : UITableViewController { - NSArray* _articles; - UISegmentedControl* _segmentedControl; + NSArray *_articles; + UISegmentedControl *_segmentedControl; } @end diff --git a/Examples/RKCatalog/Examples/RKCoreDataExample/RKCoreDataExample.m b/Examples/RKCatalog/Examples/RKCoreDataExample/RKCoreDataExample.m index 5bdb5e1173..aab4863a73 100644 --- a/Examples/RKCatalog/Examples/RKCoreDataExample/RKCoreDataExample.m +++ b/Examples/RKCatalog/Examples/RKCoreDataExample/RKCoreDataExample.m @@ -12,9 +12,9 @@ @interface Article : NSManagedObject { } -@property (nonatomic, retain) NSNumber* articleID; -@property (nonatomic, retain) NSString* title; -@property (nonatomic, retain) NSString* body; +@property (nonatomic, retain) NSNumber *articleID; +@property (nonatomic, retain) NSString *title; +@property (nonatomic, retain) NSString *body; @end @@ -31,17 +31,18 @@ @implementation Article @implementation RKCoreDataExample -- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { +- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil +{ self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { - RKObjectManager* manager = [RKObjectManager managerWithBaseURLString:@"http://restkit.org"]; + RKObjectManager *manager = [RKObjectManager managerWithBaseURLString:@"http://restkit.org"]; manager.objectStore = [RKManagedObjectStore objectStoreWithStoreFilename:@"RKCoreDataExample.sqlite"]; [RKObjectManager setSharedManager:manager]; // Create some starter objects if the database is empty if ([Article count:nil] == 0) { for (int i = 1; i <= 5; i++) { - Article* article = [Article object]; + Article *article = [Article object]; article.articleID = [NSNumber numberWithInt:i]; article.title = [NSString stringWithFormat:@"Article %d", i]; article.body = @"This is the body"; @@ -51,7 +52,7 @@ - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil } } - NSArray* items = [NSArray arrayWithObjects:@"All", @"Sorted", @"By Predicate", @"By ID", nil]; + NSArray *items = [NSArray arrayWithObjects:@"All", @"Sorted", @"By Predicate", @"By ID", nil]; _segmentedControl = [[UISegmentedControl alloc] initWithItems:items]; _segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar; _segmentedControl.momentary = NO; @@ -62,23 +63,27 @@ - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil return self; } -- (void)dealloc { +- (void)dealloc +{ [_articles release]; [_segmentedControl release]; [super dealloc]; } -- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section { +- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section +{ return 35; } -- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { +- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section +{ return _segmentedControl; } -- (NSFetchRequest*)fetchRequestForSelectedSegment { - NSFetchRequest* fetchRequest = [Article fetchRequest]; - NSPredicate* predicate = nil; +- (NSFetchRequest *)fetchRequestForSelectedSegment +{ + NSFetchRequest *fetchRequest = [Article fetchRequest]; + NSPredicate *predicate = nil; switch (_segmentedControl.selectedSegmentIndex) { // All objects @@ -89,7 +94,7 @@ - (NSFetchRequest*)fetchRequestForSelectedSegment { // Sorted case 1:; - NSSortDescriptor* sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"title" ascending:NO]; + NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"title" ascending:NO]; [fetchRequest setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]]; break; @@ -114,28 +119,32 @@ - (NSFetchRequest*)fetchRequestForSelectedSegment { return fetchRequest; } -- (void)updateTableView { +- (void)updateTableView +{ [_articles release]; - NSFetchRequest* fetchRequest = [self fetchRequestForSelectedSegment]; + NSFetchRequest *fetchRequest = [self fetchRequestForSelectedSegment]; _articles = [[Article objectsWithFetchRequest:fetchRequest] retain]; [self.tableView reloadData]; } -- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { +- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView +{ return 1; } -- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { +- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section +{ return [_articles count]; } -- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { - UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"ArticleCell"]; +- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath +{ + UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ArticleCell"]; if (nil == cell) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ArticleCell"] autorelease]; } - Article* article = [_articles objectAtIndex:indexPath.row]; + Article *article = [_articles objectAtIndex:indexPath.row]; cell.textLabel.text = article.title; cell.detailTextLabel.text = article.body; diff --git a/Examples/RKCatalog/Examples/RKKeyValueMappingExample/RKKeyValueMappingExample.h b/Examples/RKCatalog/Examples/RKKeyValueMappingExample/RKKeyValueMappingExample.h index 09ae2ec400..e424a5d18a 100644 --- a/Examples/RKCatalog/Examples/RKKeyValueMappingExample/RKKeyValueMappingExample.h +++ b/Examples/RKCatalog/Examples/RKKeyValueMappingExample/RKKeyValueMappingExample.h @@ -9,9 +9,9 @@ #import "RKCatalog.h" @interface RKKeyValueMappingExample : UIViewController { - UILabel* _infoLabel; + UILabel *_infoLabel; } -@property (nonatomic, retain) IBOutlet UILabel* infoLabel; +@property (nonatomic, retain) IBOutlet UILabel *infoLabel; @end diff --git a/Examples/RKCatalog/Examples/RKKeyValueMappingExample/RKKeyValueMappingExample.m b/Examples/RKCatalog/Examples/RKKeyValueMappingExample/RKKeyValueMappingExample.m index c5e69b9a76..4f0259098d 100644 --- a/Examples/RKCatalog/Examples/RKKeyValueMappingExample/RKKeyValueMappingExample.m +++ b/Examples/RKCatalog/Examples/RKKeyValueMappingExample/RKKeyValueMappingExample.m @@ -13,20 +13,20 @@ This code is excerpted from the Advanced Tutorial. See Docs/ for explanation */ @interface SimpleAccount : NSObject { - NSNumber* _accountID; - NSString* _name; - NSNumber* _balance; - NSNumber* _transactionsCount; - NSNumber* _averageTransactionAmount; - NSArray* _distinctPayees; + NSNumber *_accountID; + NSString *_name; + NSNumber *_balance; + NSNumber *_transactionsCount; + NSNumber *_averageTransactionAmount; + NSArray *_distinctPayees; } -@property (nonatomic, retain) NSNumber* accountID; -@property (nonatomic, retain) NSString* name; -@property (nonatomic, retain) NSNumber* balance; -@property (nonatomic, retain) NSNumber* transactionsCount; -@property (nonatomic, retain) NSNumber* averageTransactionAmount; -@property (nonatomic, retain) NSArray* distinctPayees; +@property (nonatomic, retain) NSNumber *accountID; +@property (nonatomic, retain) NSString *name; +@property (nonatomic, retain) NSNumber *balance; +@property (nonatomic, retain) NSNumber *transactionsCount; +@property (nonatomic, retain) NSNumber *averageTransactionAmount; +@property (nonatomic, retain) NSArray *distinctPayees; @end @@ -48,7 +48,8 @@ @implementation RKKeyValueMappingExample @synthesize infoLabel = _infoLabel; -- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { +- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil +{ self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { [RKObjectManager managerWithBaseURL:gRKCatalogBaseURL]; @@ -57,10 +58,11 @@ - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil return self; } -- (void)viewDidAppear:(BOOL)animated { +- (void)viewDidAppear:(BOOL)animated +{ [super viewDidAppear:animated]; - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[SimpleAccount class]]; + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[SimpleAccount class]]; [mapping mapKeyPathsToAttributes: @"id", @"accountID", @"name", @"name", @@ -74,10 +76,11 @@ - (void)viewDidAppear:(BOOL)animated { [[RKObjectManager sharedManager] loadObjectsAtResourcePath:@"/RKKeyValueMappingExample" delegate:self]; } -- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObjects:(NSArray*)objects { - SimpleAccount* account = [objects objectAtIndex:0]; +- (void)objectLoader:(RKObjectLoader *)objectLoader didLoadObjects:(NSArray *)objects +{ + SimpleAccount *account = [objects objectAtIndex:0]; - NSString* info = [NSString stringWithFormat: + NSString *info = [NSString stringWithFormat: @"The count is %@\n" @"The average transaction amount is %@\n" @"The distinct list of payees is: %@", @@ -87,7 +90,8 @@ - (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObjects:(NSArray*)obje _infoLabel.text = info; } -- (void)objectLoader:(RKObjectLoader *)objectLoader didFailWithError:(NSError *)error { +- (void)objectLoader:(RKObjectLoader *)objectLoader didFailWithError:(NSError *)error +{ _infoLabel.text = [NSString stringWithFormat:@"Error: %@", [error localizedDescription]]; _infoLabel.textColor = [UIColor redColor]; } diff --git a/Examples/RKCatalog/Examples/RKParamsExample/RKParamsExample.h b/Examples/RKCatalog/Examples/RKParamsExample/RKParamsExample.h index fe2654c621..b74d16ef0a 100644 --- a/Examples/RKCatalog/Examples/RKParamsExample/RKParamsExample.h +++ b/Examples/RKCatalog/Examples/RKParamsExample/RKParamsExample.h @@ -9,19 +9,19 @@ #import "RKCatalog.h" @interface RKParamsExample : UIViewController { - RKClient* _client; - UIProgressView* _progressView; - UIActivityIndicatorView* _activityIndicatorView; - UIImageView* _imageView; - UIButton* _uploadButton; - UILabel* _statusLabel; + RKClient *_client; + UIProgressView *_progressView; + UIActivityIndicatorView *_activityIndicatorView; + UIImageView *_imageView; + UIButton *_uploadButton; + UILabel *_statusLabel; } -@property (nonatomic, retain) IBOutlet UIProgressView* progressView; -@property (nonatomic, retain) IBOutlet UIActivityIndicatorView* activityIndicatorView; -@property (nonatomic, retain) IBOutlet UIImageView* imageView; -@property (nonatomic, retain) IBOutlet UIButton* uploadButton; -@property (nonatomic, retain) IBOutlet UILabel* statusLabel; +@property (nonatomic, retain) IBOutlet UIProgressView *progressView; +@property (nonatomic, retain) IBOutlet UIActivityIndicatorView *activityIndicatorView; +@property (nonatomic, retain) IBOutlet UIImageView *imageView; +@property (nonatomic, retain) IBOutlet UIButton *uploadButton; +@property (nonatomic, retain) IBOutlet UILabel *statusLabel; - (IBAction)uploadButtonWasTouched:(id)sender; diff --git a/Examples/RKCatalog/Examples/RKParamsExample/RKParamsExample.m b/Examples/RKCatalog/Examples/RKParamsExample/RKParamsExample.m index f7e96d3b47..ea1ad516b0 100644 --- a/Examples/RKCatalog/Examples/RKParamsExample/RKParamsExample.m +++ b/Examples/RKCatalog/Examples/RKParamsExample/RKParamsExample.m @@ -16,26 +16,29 @@ @implementation RKParamsExample @synthesize uploadButton = _uploadButton; @synthesize statusLabel = _statusLabel; -- (void)dealloc { +- (void)dealloc +{ [RKClient setSharedClient:nil]; [_client release]; [super dealloc]; } -- (void)viewDidLoad { +- (void)viewDidLoad +{ _client = [[RKClient alloc] initWithBaseURL:gRKCatalogBaseURL]; } -- (IBAction)uploadButtonWasTouched:(id)sender { - RKParams* params = [RKParams params]; +- (IBAction)uploadButtonWasTouched:(id)sender +{ + RKParams *params = [RKParams params]; // Attach the Image from Image View NSLog(@"Got image: %@", [_imageView image]); - NSData* imageData = UIImagePNGRepresentation([_imageView image]); + NSData *imageData = UIImagePNGRepresentation([_imageView image]); [params setData:imageData MIMEType:@"image/png" forParam:@"image1"]; // Attach an Image from the App Bundle - UIImage* image = [UIImage imageNamed:@"RestKit.png"]; + UIImage *image = [UIImage imageNamed:@"RestKit.png"]; imageData = UIImagePNGRepresentation(image); [params setData:imageData MIMEType:@"image/png" forParam:@"image2"]; @@ -47,16 +50,19 @@ - (IBAction)uploadButtonWasTouched:(id)sender { [_client post:@"/RKParamsExample" params:params delegate:self]; } -- (void)requestDidStartLoad:(RKRequest *)request { +- (void)requestDidStartLoad:(RKRequest *)request +{ _uploadButton.enabled = NO; [_activityIndicatorView startAnimating]; } -- (void)request:(RKRequest *)request didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite { +- (void)request:(RKRequest *)request didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite +{ _progressView.progress = (totalBytesWritten / totalBytesExpectedToWrite) * 100.0; } -- (void)request:(RKRequest *)request didLoadResponse:(RKResponse *)response { +- (void)request:(RKRequest *)request didLoadResponse:(RKResponse *)response +{ _uploadButton.enabled = YES; [_activityIndicatorView stopAnimating]; @@ -69,7 +75,8 @@ - (void)request:(RKRequest *)request didLoadResponse:(RKResponse *)response { } } -- (void)request:(RKRequest *)request didFailLoadWithError:(NSError *)error { +- (void)request:(RKRequest *)request didFailLoadWithError:(NSError *)error +{ _uploadButton.enabled = YES; [_activityIndicatorView stopAnimating]; _progressView.progress = 0.0; diff --git a/Examples/RKCatalog/Examples/RKReachabilityExample/RKReachabilityExample.m b/Examples/RKCatalog/Examples/RKReachabilityExample/RKReachabilityExample.m index c6fdceebf6..534cfa887d 100644 --- a/Examples/RKCatalog/Examples/RKReachabilityExample/RKReachabilityExample.m +++ b/Examples/RKCatalog/Examples/RKReachabilityExample/RKReachabilityExample.m @@ -15,7 +15,8 @@ @implementation RKReachabilityExample @synthesize statusLabel = _statusLabel; @synthesize flagsLabel = _flagsLabel; -- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { +- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil +{ self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { self.observer = [[RKReachabilityObserver alloc] initWithHost:@"restkit.org"]; @@ -32,21 +33,24 @@ - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil return self; } -- (void)dealloc { +- (void)dealloc +{ [[NSNotificationCenter defaultCenter] removeObserver:self]; [_observer release]; [super dealloc]; } -- (void)viewDidLoad { +- (void)viewDidLoad +{ if (! [_observer isReachabilityDetermined]) { _statusLabel.text = @"Reachability is indeterminate..."; _statusLabel.textColor = [UIColor blueColor]; } } -- (void)reachabilityChanged:(NSNotification *)notification { - RKReachabilityObserver* observer = (RKReachabilityObserver *) [notification object]; +- (void)reachabilityChanged:(NSNotification *)notification +{ + RKReachabilityObserver *observer = (RKReachabilityObserver *)[notification object]; RKLogCritical(@"Received reachability update: %@", observer); _flagsLabel.text = [NSString stringWithFormat:@"Host: %@ -> %@", observer.host, [observer reachabilityFlagsDescription]]; diff --git a/Examples/RKCatalog/Examples/RKRelationshipMappingExample/Project.h b/Examples/RKCatalog/Examples/RKRelationshipMappingExample/Project.h index 5e28401b66..5ae4e0e223 100644 --- a/Examples/RKCatalog/Examples/RKRelationshipMappingExample/Project.h +++ b/Examples/RKCatalog/Examples/RKRelationshipMappingExample/Project.h @@ -10,17 +10,17 @@ #import "User.h" @interface Project : NSObject { - NSNumber* _projectID; - NSString* _name; - NSString* _description; - User* _user; - NSArray* _tasks; + NSNumber *_projectID; + NSString *_name; + NSString *_description; + User *_user; + NSArray *_tasks; } -@property (nonatomic, retain) NSNumber* projectID; -@property (nonatomic, retain) NSString* name; -@property (nonatomic, retain) NSString* description; -@property (nonatomic, retain) User* user; -@property (nonatomic, retain) NSArray* tasks; +@property (nonatomic, retain) NSNumber *projectID; +@property (nonatomic, retain) NSString *name; +@property (nonatomic, retain) NSString *description; +@property (nonatomic, retain) User *user; +@property (nonatomic, retain) NSArray *tasks; @end diff --git a/Examples/RKCatalog/Examples/RKRelationshipMappingExample/RKRelationshipMappingExample.h b/Examples/RKCatalog/Examples/RKRelationshipMappingExample/RKRelationshipMappingExample.h index 3bc144eeb5..f7e35b2e6a 100644 --- a/Examples/RKCatalog/Examples/RKRelationshipMappingExample/RKRelationshipMappingExample.h +++ b/Examples/RKCatalog/Examples/RKRelationshipMappingExample/RKRelationshipMappingExample.h @@ -10,8 +10,8 @@ #import "Project.h" @interface RKRelationshipMappingExample : UITableViewController { - Project* _selectedProject; - NSArray* _objects; + Project *_selectedProject; + NSArray *_objects; } @end diff --git a/Examples/RKCatalog/Examples/RKRelationshipMappingExample/RKRelationshipMappingExample.m b/Examples/RKCatalog/Examples/RKRelationshipMappingExample/RKRelationshipMappingExample.m index d3a006237e..4642e00bad 100644 --- a/Examples/RKCatalog/Examples/RKRelationshipMappingExample/RKRelationshipMappingExample.m +++ b/Examples/RKCatalog/Examples/RKRelationshipMappingExample/RKRelationshipMappingExample.m @@ -15,21 +15,22 @@ @implementation RKRelationshipMappingExample -- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { +- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil +{ self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { - RKObjectManager* objectManager = [RKObjectManager managerWithBaseURL:gRKCatalogBaseURL]; + RKObjectManager *objectManager = [RKObjectManager managerWithBaseURL:gRKCatalogBaseURL]; RKManagedObjectStore *objectStore = [RKManagedObjectStore objectStoreWithStoreFilename:@"RKRelationshipMappingExample.sqlite"]; objectManager.objectStore = objectStore; - RKManagedObjectMapping* taskMapping = [RKManagedObjectMapping mappingForClass:[Task class] inManagedObjectStore:objectStore]; + RKManagedObjectMapping *taskMapping = [RKManagedObjectMapping mappingForClass:[Task class] inManagedObjectStore:objectStore]; taskMapping.primaryKeyAttribute = @"taskID"; [taskMapping mapKeyPath:@"id" toAttribute:@"taskID"]; [taskMapping mapKeyPath:@"name" toAttribute:@"name"]; [taskMapping mapKeyPath:@"assigned_user_id" toAttribute:@"assignedUserID"]; [objectManager.mappingProvider setMapping:taskMapping forKeyPath:@"task"]; - RKManagedObjectMapping* userMapping = [RKManagedObjectMapping mappingForClass:[User class] inManagedObjectStore:objectStore]; + RKManagedObjectMapping *userMapping = [RKManagedObjectMapping mappingForClass:[User class] inManagedObjectStore:objectStore]; userMapping.primaryKeyAttribute = @"userID"; [userMapping mapAttributes:@"name", @"email", nil]; [userMapping mapKeyPath:@"id" toAttribute:@"userID"]; @@ -41,7 +42,7 @@ - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil [taskMapping connectRelationship:@"assignedUser" withObjectForPrimaryKeyAttribute:@"assignedUserID"]; // NOTE - Project is not backed by Core Data - RKObjectMapping* projectMapping = [RKObjectMapping mappingForClass:[Project class]]; + RKObjectMapping *projectMapping = [RKObjectMapping mappingForClass:[Project class]]; [projectMapping mapKeyPath:@"id" toAttribute:@"projectID"]; [projectMapping mapAttributes:@"name", @"description", nil]; [projectMapping mapRelationship:@"user" withMapping:userMapping]; @@ -52,12 +53,14 @@ - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil return self; } -- (void)dealloc { +- (void)dealloc +{ [_objects release]; [super dealloc]; } -- (void)viewDidAppear:(BOOL)animated { +- (void)viewDidAppear:(BOOL)animated +{ [super viewDidAppear:animated]; self.title = @"Task List"; @@ -65,30 +68,34 @@ - (void)viewDidAppear:(BOOL)animated { [[RKObjectManager sharedManager] loadObjectsAtResourcePath:@"/RKRelationshipMappingExample" delegate:self]; } -- (void)objectLoader:(RKObjectLoader *)objectLoader didLoadObjects:(NSArray *)objects { +- (void)objectLoader:(RKObjectLoader *)objectLoader didLoadObjects:(NSArray *)objects +{ _objects = [objects retain]; [self.tableView reloadData]; } -- (void)objectLoader:(RKObjectLoader *)objectLoader didFailWithError:(NSError *)error { - UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Error!" message:[error localizedDescription] delegate:nil cancelButtonTitle:@"Rats!" otherButtonTitles:nil]; +- (void)objectLoader:(RKObjectLoader *)objectLoader didFailWithError:(NSError *)error +{ + UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error!" message:[error localizedDescription] delegate:nil cancelButtonTitle:@"Rats!" otherButtonTitles:nil]; [alert show]; [alert release]; } #pragma mark - Table view data source -- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { +- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView +{ return 2; } -- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { +- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section +{ if (section == 0) { // Return number of projects return [_objects count]; } else { // Return number of tasks in the selected project... - NSIndexPath* indexPath = [self.tableView indexPathForSelectedRow]; + NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow]; if (indexPath) { return [[[_objects objectAtIndex:indexPath.row] tasks] count]; } @@ -97,8 +104,9 @@ - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger return 0; } -- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { - UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, 150, 100)]; +- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section +{ + UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, 150, 100)]; label.backgroundColor = [UIColor clearColor]; label.font = [UIFont boldSystemFontOfSize:18]; @@ -113,7 +121,8 @@ - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger #pragma mark - Table View Selection -- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath { +- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath +{ // Don't allow selections in the bottom section if (indexPath.section == 1) { return nil; @@ -122,16 +131,18 @@ - (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NS return indexPath; } -- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { +- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath +{ [_selectedProject release]; _selectedProject = [[_objects objectAtIndex:indexPath.row] retain]; [self.tableView reloadData]; - UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath]; + UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; cell.accessoryType = UITableViewCellAccessoryCheckmark; } -- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { +- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath +{ static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; @@ -140,13 +151,13 @@ - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(N } if (indexPath.section == 0) { - Project* project = (Project*) [_objects objectAtIndex:indexPath.row]; + Project *project = (Project *)[_objects objectAtIndex:indexPath.row]; cell.accessoryType = UITableViewCellAccessoryNone; cell.textLabel.text = project.name; } else if (indexPath.section == 1) { // NOTE: We refetch the object here because Project is not Core Data backed - NSManagedObject* objectReference = [_selectedProject.tasks objectAtIndex:indexPath.row]; - Task* task = (Task*) [[RKObjectManager sharedManager].objectStore objectWithID:[objectReference objectID]]; + NSManagedObject *objectReference = [_selectedProject.tasks objectAtIndex:indexPath.row]; + Task *task = (Task *)[[RKObjectManager sharedManager].objectStore objectWithID:[objectReference objectID]]; cell.textLabel.text = [NSString stringWithFormat:@"%@", task.name]; cell.detailTextLabel.text = [NSString stringWithFormat:@"Assigned to: %@", task.assignedUser.name]; } diff --git a/Examples/RKCatalog/Examples/RKRelationshipMappingExample/Task.h b/Examples/RKCatalog/Examples/RKRelationshipMappingExample/Task.h index 29673d84ba..44d59b8036 100644 --- a/Examples/RKCatalog/Examples/RKRelationshipMappingExample/Task.h +++ b/Examples/RKCatalog/Examples/RKRelationshipMappingExample/Task.h @@ -12,9 +12,9 @@ @interface Task : NSManagedObject { } -@property (nonatomic, retain) NSString* name; -@property (nonatomic, retain) NSNumber* taskID; -@property (nonatomic, retain) NSNumber* assignedUserID; -@property (nonatomic, retain) User* assignedUser; +@property (nonatomic, retain) NSString *name; +@property (nonatomic, retain) NSNumber *taskID; +@property (nonatomic, retain) NSNumber *assignedUserID; +@property (nonatomic, retain) User *assignedUser; @end diff --git a/Examples/RKCatalog/Examples/RKRelationshipMappingExample/User.h b/Examples/RKCatalog/Examples/RKRelationshipMappingExample/User.h index 7cdf5a0bc4..500ea6392d 100644 --- a/Examples/RKCatalog/Examples/RKRelationshipMappingExample/User.h +++ b/Examples/RKCatalog/Examples/RKRelationshipMappingExample/User.h @@ -11,9 +11,9 @@ @interface User : NSManagedObject { } -@property (nonatomic, retain) NSNumber* userID; -@property (nonatomic, retain) NSString* name; -@property (nonatomic, retain) NSString* email; -@property (nonatomic, retain) NSSet* tasks; +@property (nonatomic, retain) NSNumber *userID; +@property (nonatomic, retain) NSString *name; +@property (nonatomic, retain) NSString *email; +@property (nonatomic, retain) NSSet *tasks; @end diff --git a/Examples/RKCatalog/Examples/RKRequestQueueExample/RKRequestQueueExample.m b/Examples/RKCatalog/Examples/RKRequestQueueExample/RKRequestQueueExample.m index 941193a832..807ccba7ab 100644 --- a/Examples/RKCatalog/Examples/RKRequestQueueExample/RKRequestQueueExample.m +++ b/Examples/RKCatalog/Examples/RKRequestQueueExample/RKRequestQueueExample.m @@ -14,10 +14,11 @@ @implementation RKRequestQueueExample @synthesize requestQueue; @synthesize statusLabel; -- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { +- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil +{ self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { - RKClient* client = [RKClient clientWithBaseURL:gRKCatalogBaseURL]; + RKClient *client = [RKClient clientWithBaseURL:gRKCatalogBaseURL]; [RKClient setSharedClient:client]; // Ask RestKit to spin the network activity indicator for us @@ -29,7 +30,8 @@ - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil } // We have been dismissed -- clean up any open requests -- (void)dealloc { +- (void)dealloc +{ [[RKClient sharedClient].requestQueue cancelRequestsWithDelegate:self]; [requestQueue cancelAllRequests]; [requestQueue release]; @@ -39,11 +41,13 @@ - (void)dealloc { } // We have been obscured -- cancel any pending requests -- (void)viewWillDisappear:(BOOL)animated { +- (void)viewWillDisappear:(BOOL)animated +{ [[RKClient sharedClient].requestQueue cancelRequestsWithDelegate:self]; } -- (IBAction)sendRequest { +- (IBAction)sendRequest +{ /** * Ask RKClient to load us some data. This causes an RKRequest object to be created * transparently pushed onto the RKClient's RKRequestQueue instance @@ -51,7 +55,8 @@ - (IBAction)sendRequest { [[RKClient sharedClient] get:@"/RKRequestQueueExample" delegate:self]; } -- (IBAction)queueRequests { +- (IBAction)queueRequests +{ RKRequestQueue *queue = [RKRequestQueue requestQueue]; queue.delegate = self; queue.concurrentRequestsLimit = 1; @@ -79,16 +84,19 @@ - (IBAction)queueRequests { self.requestQueue = queue; } -- (void)requestQueue:(RKRequestQueue *)queue didSendRequest:(RKRequest *)request { +- (void)requestQueue:(RKRequestQueue *)queue didSendRequest:(RKRequest *)request +{ statusLabel.text = [NSString stringWithFormat:@"RKRequestQueue %@ is current loading %d of %d requests", queue, [queue loadingCount], [queue count]]; } -- (void)requestQueueDidBeginLoading:(RKRequestQueue *)queue { +- (void)requestQueueDidBeginLoading:(RKRequestQueue *)queue +{ statusLabel.text = [NSString stringWithFormat:@"Queue %@ Began Loading...", queue]; } -- (void)requestQueueDidFinishLoading:(RKRequestQueue *)queue { +- (void)requestQueueDidFinishLoading:(RKRequestQueue *)queue +{ statusLabel.text = [NSString stringWithFormat:@"Queue %@ Finished Loading...", queue]; } diff --git a/Examples/RKMacOSX/RKMacOSX/RKMacOSXAppDelegate.m b/Examples/RKMacOSX/RKMacOSX/RKMacOSXAppDelegate.m index 1f44acafab..9b2a146763 100644 --- a/Examples/RKMacOSX/RKMacOSX/RKMacOSXAppDelegate.m +++ b/Examples/RKMacOSX/RKMacOSX/RKMacOSXAppDelegate.m @@ -20,11 +20,13 @@ - (void)applicationDidFinishLaunching:(NSNotification *)aNotification [self.client get:@"/status/user_timeline/RestKit.json" delegate:self]; } -- (void)request:(RKRequest*)request didLoadResponse:(RKResponse *)response { +- (void)request:(RKRequest *)request didLoadResponse:(RKResponse *)response +{ NSLog(@"Loaded JSON: %@", [response bodyAsString]); } -- (void)dealloc { +- (void)dealloc +{ [super dealloc]; } diff --git a/Examples/RKTwitter/Classes/RKTStatus.h b/Examples/RKTwitter/Classes/RKTStatus.h index a3c23afef8..b5aa902315 100644 --- a/Examples/RKTwitter/Classes/RKTStatus.h +++ b/Examples/RKTwitter/Classes/RKTStatus.h @@ -9,48 +9,48 @@ #import "RKTUser.h" @interface RKTStatus : NSObject { - NSNumber* _statusID; - NSDate* _createdAt; - NSString* _text; - NSString* _urlString; - NSString* _inReplyToScreenName; - NSNumber* _isFavorited; - RKTUser* _user; + NSNumber *_statusID; + NSDate *_createdAt; + NSString *_text; + NSString *_urlString; + NSString *_inReplyToScreenName; + NSNumber *_isFavorited; + RKTUser *_user; } /** * The unique ID of this Status */ -@property (nonatomic, retain) NSNumber* statusID; +@property (nonatomic, retain) NSNumber *statusID; /** * Timestamp the Status was sent */ -@property (nonatomic, retain) NSDate* createdAt; +@property (nonatomic, retain) NSDate *createdAt; /** * Text of the Status */ -@property (nonatomic, retain) NSString* text; +@property (nonatomic, retain) NSString *text; /** * String version of the URL associated with the Status */ -@property (nonatomic, retain) NSString* urlString; +@property (nonatomic, retain) NSString *urlString; /** * The screen name of the User this Status was in response to */ -@property (nonatomic, retain) NSString* inReplyToScreenName; +@property (nonatomic, retain) NSString *inReplyToScreenName; /** * Is this status a favorite? */ -@property (nonatomic, retain) NSNumber* isFavorited; +@property (nonatomic, retain) NSNumber *isFavorited; /** * The User who posted this status */ -@property (nonatomic, retain) RKTUser* user; +@property (nonatomic, retain) RKTUser *user; @end diff --git a/Examples/RKTwitter/Classes/RKTStatus.m b/Examples/RKTwitter/Classes/RKTStatus.m index 0bbf464549..7fdcad540f 100644 --- a/Examples/RKTwitter/Classes/RKTStatus.m +++ b/Examples/RKTwitter/Classes/RKTStatus.m @@ -18,11 +18,13 @@ @implementation RKTStatus @synthesize isFavorited = _isFavorited; @synthesize user = _user; -- (NSString*)description { +- (NSString *)description +{ return [NSString stringWithFormat:@"%@ (ID: %@)", self.text, self.statusID]; } -- (void)dealloc { +- (void)dealloc +{ [_statusID release]; [_createdAt release]; [_text release]; diff --git a/Examples/RKTwitter/Classes/RKTUser.h b/Examples/RKTwitter/Classes/RKTUser.h index 20a6508b61..fe5468588b 100644 --- a/Examples/RKTwitter/Classes/RKTUser.h +++ b/Examples/RKTwitter/Classes/RKTUser.h @@ -7,13 +7,13 @@ // @interface RKTUser : NSObject { - NSNumber* _userID; - NSString* _name; - NSString* _screenName; + NSNumber *_userID; + NSString *_name; + NSString *_screenName; } -@property (nonatomic, retain) NSNumber* userID; -@property (nonatomic, retain) NSString* name; -@property (nonatomic, retain) NSString* screenName; +@property (nonatomic, retain) NSNumber *userID; +@property (nonatomic, retain) NSString *name; +@property (nonatomic, retain) NSString *screenName; @end diff --git a/Examples/RKTwitter/Classes/RKTUser.m b/Examples/RKTwitter/Classes/RKTUser.m index aabd1d5f3b..7e241bfff2 100644 --- a/Examples/RKTwitter/Classes/RKTUser.m +++ b/Examples/RKTwitter/Classes/RKTUser.m @@ -14,7 +14,8 @@ @implementation RKTUser @synthesize name = _name; @synthesize screenName = _screenName; -- (void)dealloc { +- (void)dealloc +{ [_userID release]; [_name release]; [_screenName release]; diff --git a/Examples/RKTwitter/Classes/RKTwitterAppDelegate.m b/Examples/RKTwitter/Classes/RKTwitterAppDelegate.m index 7fa71dbe53..9740c1a2f8 100644 --- a/Examples/RKTwitter/Classes/RKTwitterAppDelegate.m +++ b/Examples/RKTwitter/Classes/RKTwitterAppDelegate.m @@ -17,23 +17,24 @@ @implementation RKTwitterAppDelegate #pragma mark - #pragma mark Application lifecycle -- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { +- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions +{ RKLogConfigureByName("RestKit/Network*", RKLogLevelTrace); RKLogConfigureByName("RestKit/ObjectMapping", RKLogLevelTrace); // Initialize RestKit - RKObjectManager* objectManager = [RKObjectManager managerWithBaseURLString:@"http://twitter.com"]; + RKObjectManager *objectManager = [RKObjectManager managerWithBaseURLString:@"http://twitter.com"]; // Enable automatic network activity indicator management objectManager.client.requestQueue.showsNetworkActivityIndicatorWhenBusy = YES; // Setup our object mappings - RKObjectMapping* userMapping = [RKObjectMapping mappingForClass:[RKTUser class]]; + RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTUser class]]; [userMapping mapKeyPath:@"id" toAttribute:@"userID"]; [userMapping mapKeyPath:@"screen_name" toAttribute:@"screenName"]; [userMapping mapAttributes:@"name", nil]; - RKObjectMapping* statusMapping = [RKObjectMapping mappingForClass:[RKTStatus class]]; + RKObjectMapping *statusMapping = [RKObjectMapping mappingForClass:[RKTStatus class]]; [statusMapping mapKeyPathsToAttributes:@"id", @"statusID", @"created_at", @"createdAt", @"text", @"text", @@ -55,16 +56,17 @@ - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:( [objectManager.mappingProvider setObjectMapping:statusMapping forResourcePathPattern:@"/status/user_timeline/:username"]; // Create Window and View Controllers - RKTwitterViewController* viewController = [[[RKTwitterViewController alloc] initWithNibName:nil bundle:nil] autorelease]; - UINavigationController* controller = [[UINavigationController alloc] initWithRootViewController:viewController]; - UIWindow* window = [[UIWindow alloc] initWithFrame:CGRectMake(0, 0, 320, 480)]; + RKTwitterViewController *viewController = [[[RKTwitterViewController alloc] initWithNibName:nil bundle:nil] autorelease]; + UINavigationController *controller = [[UINavigationController alloc] initWithRootViewController:viewController]; + UIWindow *window = [[UIWindow alloc] initWithFrame:CGRectMake(0, 0, 320, 480)]; [window addSubview:controller.view]; [window makeKeyAndVisible]; return YES; } -- (void)dealloc { +- (void)dealloc +{ [super dealloc]; } diff --git a/Examples/RKTwitter/Classes/RKTwitterViewController.h b/Examples/RKTwitter/Classes/RKTwitterViewController.h index 19abdbbf83..73cf07ddf0 100644 --- a/Examples/RKTwitter/Classes/RKTwitterViewController.h +++ b/Examples/RKTwitter/Classes/RKTwitterViewController.h @@ -10,8 +10,8 @@ #import @interface RKTwitterViewController : UIViewController { - UITableView* _tableView; - NSArray* _statuses; + UITableView *_tableView; + NSArray *_statuses; } @end diff --git a/Examples/RKTwitter/Classes/RKTwitterViewController.m b/Examples/RKTwitter/Classes/RKTwitterViewController.m index 6e985a9b92..7303ce6df7 100644 --- a/Examples/RKTwitter/Classes/RKTwitterViewController.m +++ b/Examples/RKTwitter/Classes/RKTwitterViewController.m @@ -15,14 +15,16 @@ - (void)loadData; @implementation RKTwitterViewController -- (void)loadTimeline { +- (void)loadTimeline +{ // Load the object model via RestKit - RKObjectManager* objectManager = [RKObjectManager sharedManager]; + RKObjectManager *objectManager = [RKObjectManager sharedManager]; objectManager.client.baseURL = [RKURL URLWithString:@"http://www.twitter.com"]; [objectManager loadObjectsAtResourcePath:@"/status/user_timeline/RestKit" delegate:self]; } -- (void)loadView { +- (void)loadView +{ [super loadView]; // Setup View and Table View @@ -31,7 +33,7 @@ - (void)loadView { self.navigationController.navigationBar.tintColor = [UIColor blackColor]; self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(loadTimeline)] autorelease]; - UIImageView* imageView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"BG.png"]] autorelease]; + UIImageView *imageView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"BG.png"]] autorelease]; imageView.frame = CGRectOffset(imageView.frame, 0, -64); [self.view insertSubview:imageView atIndex:0]; @@ -46,7 +48,8 @@ - (void)loadView { [self loadTimeline]; } -- (void)dealloc { +- (void)dealloc +{ [_tableView release]; [_statuses release]; [super dealloc]; @@ -54,39 +57,45 @@ - (void)dealloc { #pragma mark RKObjectLoaderDelegate methods -- (void)request:(RKRequest*)request didLoadResponse:(RKResponse*)response { +- (void)request:(RKRequest *)request didLoadResponse:(RKResponse *)response +{ NSLog(@"Loaded payload: %@", [response bodyAsString]); } -- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObjects:(NSArray*)objects { +- (void)objectLoader:(RKObjectLoader *)objectLoader didLoadObjects:(NSArray *)objects +{ NSLog(@"Loaded statuses: %@", objects); [_statuses release]; _statuses = [objects retain]; [_tableView reloadData]; } -- (void)objectLoader:(RKObjectLoader*)objectLoader didFailWithError:(NSError*)error { - UIAlertView* alert = [[[UIAlertView alloc] initWithTitle:@"Error" message:[error localizedDescription] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease]; +- (void)objectLoader:(RKObjectLoader *)objectLoader didFailWithError:(NSError *)error +{ + UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"Error" message:[error localizedDescription] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease]; [alert show]; NSLog(@"Hit error: %@", error); } #pragma mark UITableViewDelegate methods -- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { +- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath +{ CGSize size = [[[_statuses objectAtIndex:indexPath.row] text] sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(300, 9000)]; return size.height + 10; } #pragma mark UITableViewDataSource methods -- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section { +- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section +{ return [_statuses count]; } -- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { - NSString* reuseIdentifier = @"Tweet Cell"; - UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier]; +- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath +{ + NSString *reuseIdentifier = @"Tweet Cell"; + UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier]; if (nil == cell) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier] autorelease]; cell.textLabel.font = [UIFont systemFontOfSize:14]; diff --git a/Examples/RKTwitter/main.m b/Examples/RKTwitter/main.m index 68a6317613..ac95e09847 100644 --- a/Examples/RKTwitter/main.m +++ b/Examples/RKTwitter/main.m @@ -10,7 +10,7 @@ int main(int argc, char *argv[]) { - NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; int retVal = UIApplicationMain(argc, argv, nil, @"RKTwitterAppDelegate"); [pool release]; return retVal; diff --git a/Examples/RKTwitterCoreData/Classes/RKTStatus.h b/Examples/RKTwitterCoreData/Classes/RKTStatus.h index caa1370d56..605d477e8f 100644 --- a/Examples/RKTwitterCoreData/Classes/RKTStatus.h +++ b/Examples/RKTwitterCoreData/Classes/RKTStatus.h @@ -15,27 +15,27 @@ /** * The unique ID of this Status */ -@property (nonatomic, retain) NSNumber* statusID; +@property (nonatomic, retain) NSNumber *statusID; /** * Timestamp the Status was sent */ -@property (nonatomic, retain) NSDate* createdAt; +@property (nonatomic, retain) NSDate *createdAt; /** * Text of the Status */ -@property (nonatomic, retain) NSString* text; +@property (nonatomic, retain) NSString *text; /** * String version of the URL associated with the Status */ -@property (nonatomic, retain) NSString* urlString; +@property (nonatomic, retain) NSString *urlString; /** * The screen name of the User this Status was in response to */ -@property (nonatomic, retain) NSString* inReplyToScreenName; +@property (nonatomic, retain) NSString *inReplyToScreenName; /** * Is this status a favorite? @@ -45,6 +45,6 @@ /** * The User who posted this status */ -@property (nonatomic, retain) NSManagedObject* user; +@property (nonatomic, retain) NSManagedObject *user; @end diff --git a/Examples/RKTwitterCoreData/Classes/RKTwitterAppDelegate.m b/Examples/RKTwitterCoreData/Classes/RKTwitterAppDelegate.m index bd2802a451..086b159cab 100644 --- a/Examples/RKTwitterCoreData/Classes/RKTwitterAppDelegate.m +++ b/Examples/RKTwitterCoreData/Classes/RKTwitterAppDelegate.m @@ -17,9 +17,10 @@ @implementation RKTwitterAppDelegate #pragma mark - #pragma mark Application lifecycle -- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { +- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions +{ // Initialize RestKit - RKObjectManager* objectManager = [RKObjectManager managerWithBaseURLString:@"http://twitter.com"]; + RKObjectManager *objectManager = [RKObjectManager managerWithBaseURLString:@"http://twitter.com"]; // Enable automatic network activity indicator management objectManager.client.requestQueue.showsNetworkActivityIndicatorWhenBusy = YES; @@ -41,7 +42,7 @@ - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:( name. This allows us to map back Twitter user objects directly onto NSManagedObject instances -- there is no backing model class! */ - RKManagedObjectMapping* userMapping = [RKManagedObjectMapping mappingForEntityWithName:@"RKTUser" inManagedObjectStore:objectManager.objectStore]; + RKManagedObjectMapping *userMapping = [RKManagedObjectMapping mappingForEntityWithName:@"RKTUser" inManagedObjectStore:objectManager.objectStore]; userMapping.primaryKeyAttribute = @"userID"; [userMapping mapKeyPath:@"id" toAttribute:@"userID"]; [userMapping mapKeyPath:@"screen_name" toAttribute:@"screenName"]; @@ -52,7 +53,7 @@ - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:( for you using the Active Record pattern where the class name corresponds to the entity name within Core Data. Twitter status objects will be mapped onto RKTStatus instances. */ - RKManagedObjectMapping* statusMapping = [RKManagedObjectMapping mappingForClass:[RKTStatus class] inManagedObjectStore:objectManager.objectStore]; + RKManagedObjectMapping *statusMapping = [RKManagedObjectMapping mappingForClass:[RKTStatus class] inManagedObjectStore:objectManager.objectStore]; statusMapping.primaryKeyAttribute = @"statusID"; [statusMapping mapKeyPathsToAttributes:@"id", @"statusID", @"created_at", @"createdAt", @@ -83,7 +84,7 @@ - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:( #ifdef RESTKIT_GENERATE_SEED_DB RKLogConfigureByName("RestKit/ObjectMapping", RKLogLevelInfo); RKLogConfigureByName("RestKit/CoreData", RKLogLevelTrace); - RKManagedObjectSeeder* seeder = [RKManagedObjectSeeder objectSeederWithObjectManager:objectManager]; + RKManagedObjectSeeder *seeder = [RKManagedObjectSeeder objectSeederWithObjectManager:objectManager]; // Seed the database with instances of RKTStatus from a snapshot of the RestKit Twitter timeline [seeder seedObjectsFromFile:@"restkit.json" withObjectMapping:statusMapping]; @@ -99,16 +100,17 @@ - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:( #endif // Create Window and View Controllers - RKTwitterViewController* viewController = [[[RKTwitterViewController alloc] initWithNibName:nil bundle:nil] autorelease]; - UINavigationController* controller = [[UINavigationController alloc] initWithRootViewController:viewController]; - UIWindow* window = [[UIWindow alloc] initWithFrame:CGRectMake(0, 0, 320, 480)]; + RKTwitterViewController *viewController = [[[RKTwitterViewController alloc] initWithNibName:nil bundle:nil] autorelease]; + UINavigationController *controller = [[UINavigationController alloc] initWithRootViewController:viewController]; + UIWindow *window = [[UIWindow alloc] initWithFrame:CGRectMake(0, 0, 320, 480)]; [window addSubview:controller.view]; [window makeKeyAndVisible]; return YES; } -- (void)dealloc { +- (void)dealloc +{ [super dealloc]; } diff --git a/Examples/RKTwitterCoreData/Classes/RKTwitterViewController.h b/Examples/RKTwitterCoreData/Classes/RKTwitterViewController.h index 909f46526c..0d696531cf 100644 --- a/Examples/RKTwitterCoreData/Classes/RKTwitterViewController.h +++ b/Examples/RKTwitterCoreData/Classes/RKTwitterViewController.h @@ -10,8 +10,8 @@ #import @interface RKTwitterViewController : UIViewController { - UITableView* _tableView; - NSArray* _statuses; + UITableView *_tableView; + NSArray *_statuses; } - (void)loadObjectsFromDataStore; @end diff --git a/Examples/RKTwitterCoreData/Classes/RKTwitterViewController.m b/Examples/RKTwitterCoreData/Classes/RKTwitterViewController.m index e4eb73dd2f..97818e066e 100644 --- a/Examples/RKTwitterCoreData/Classes/RKTwitterViewController.m +++ b/Examples/RKTwitterCoreData/Classes/RKTwitterViewController.m @@ -11,7 +11,8 @@ @implementation RKTwitterViewController -- (void)loadView { +- (void)loadView +{ [super loadView]; // Setup View and Table View @@ -20,7 +21,7 @@ - (void)loadView { self.navigationController.navigationBar.tintColor = [UIColor blackColor]; self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(reloadButtonWasPressed:)] autorelease]; - UIImageView* imageView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"BG.png"]] autorelease]; + UIImageView *imageView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"BG.png"]] autorelease]; imageView.frame = CGRectOffset(imageView.frame, 0, -64); [self.view insertSubview:imageView atIndex:0]; @@ -36,34 +37,39 @@ - (void)loadView { [self loadObjectsFromDataStore]; } -- (void)dealloc { +- (void)dealloc +{ [_tableView release]; [_statuses release]; [super dealloc]; } -- (void)loadObjectsFromDataStore { +- (void)loadObjectsFromDataStore +{ [_statuses release]; - NSFetchRequest* request = [RKTStatus fetchRequest]; - NSSortDescriptor* descriptor = [NSSortDescriptor sortDescriptorWithKey:@"createdAt" ascending:NO]; + NSFetchRequest *request = [RKTStatus fetchRequest]; + NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:@"createdAt" ascending:NO]; [request setSortDescriptors:[NSArray arrayWithObject:descriptor]]; _statuses = [[RKTStatus objectsWithFetchRequest:request] retain]; } -- (void)loadData { +- (void)loadData +{ // Load the object model via RestKit - RKObjectManager* objectManager = [RKObjectManager sharedManager]; + RKObjectManager *objectManager = [RKObjectManager sharedManager]; [objectManager loadObjectsAtResourcePath:@"/status/user_timeline/RestKit" delegate:self]; } -- (void)reloadButtonWasPressed:(id)sender { +- (void)reloadButtonWasPressed:(id)sender +{ // Load the object model via RestKit [self loadData]; } #pragma mark RKObjectLoaderDelegate methods -- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObjects:(NSArray*)objects { +- (void)objectLoader:(RKObjectLoader *)objectLoader didLoadObjects:(NSArray *)objects +{ [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"LastUpdatedAt"]; [[NSUserDefaults standardUserDefaults] synchronize]; NSLog(@"Loaded statuses: %@", objects); @@ -71,8 +77,9 @@ - (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObjects:(NSArray*)obje [_tableView reloadData]; } -- (void)objectLoader:(RKObjectLoader*)objectLoader didFailWithError:(NSError*)error { - UIAlertView* alert = [[[UIAlertView alloc] initWithTitle:@"Error" +- (void)objectLoader:(RKObjectLoader *)objectLoader didFailWithError:(NSError *)error +{ + UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"Error" message:[error localizedDescription] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease]; @@ -82,29 +89,33 @@ - (void)objectLoader:(RKObjectLoader*)objectLoader didFailWithError:(NSError*)er #pragma mark UITableViewDelegate methods -- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { +- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath +{ CGSize size = [[[_statuses objectAtIndex:indexPath.row] text] sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(300, 9000)]; return size.height + 10; } #pragma mark UITableViewDataSource methods -- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section { +- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section +{ return [_statuses count]; } -- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { - NSDate* lastUpdatedAt = [[NSUserDefaults standardUserDefaults] objectForKey:@"LastUpdatedAt"]; - NSString* dateString = [NSDateFormatter localizedStringFromDate:lastUpdatedAt dateStyle:NSDateFormatterShortStyle timeStyle:NSDateFormatterMediumStyle]; +- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section +{ + NSDate *lastUpdatedAt = [[NSUserDefaults standardUserDefaults] objectForKey:@"LastUpdatedAt"]; + NSString *dateString = [NSDateFormatter localizedStringFromDate:lastUpdatedAt dateStyle:NSDateFormatterShortStyle timeStyle:NSDateFormatterMediumStyle]; if (nil == dateString) { dateString = @"Never"; } return [NSString stringWithFormat:@"Last Load: %@", dateString]; } -- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { - NSString* reuseIdentifier = @"Tweet Cell"; - UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier]; +- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath +{ + NSString *reuseIdentifier = @"Tweet Cell"; + UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier]; if (nil == cell) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier] autorelease]; cell.textLabel.font = [UIFont systemFontOfSize:14]; @@ -112,7 +123,7 @@ - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(N cell.textLabel.backgroundColor = [UIColor clearColor]; cell.contentView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"listbg.png"]]; } - RKTStatus* status = [_statuses objectAtIndex:indexPath.row]; + RKTStatus *status = [_statuses objectAtIndex:indexPath.row]; cell.textLabel.text = status.text; return cell; } diff --git a/Examples/RKTwitterCoreData/main.m b/Examples/RKTwitterCoreData/main.m index 68a6317613..ac95e09847 100644 --- a/Examples/RKTwitterCoreData/main.m +++ b/Examples/RKTwitterCoreData/main.m @@ -10,7 +10,7 @@ int main(int argc, char *argv[]) { - NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; int retVal = UIApplicationMain(argc, argv, nil, @"RKTwitterAppDelegate"); [pool release]; return retVal; diff --git a/Examples/RestKit CLI/RestKit CLI/main.m b/Examples/RestKit CLI/RestKit CLI/main.m index b3ea0cf162..7029e05900 100644 --- a/Examples/RestKit CLI/RestKit CLI/main.m +++ b/Examples/RestKit CLI/RestKit CLI/main.m @@ -9,7 +9,7 @@ #import #import -int main (int argc, const char * argv[]) +int main (int argc, const char *argv[]) { @autoreleasepool { diff --git a/Tests/Application/UI/RKFetchedResultsTableControllerTest.m b/Tests/Application/UI/RKFetchedResultsTableControllerTest.m index 70430320e0..87cc0e763d 100644 --- a/Tests/Application/UI/RKFetchedResultsTableControllerTest.m +++ b/Tests/Application/UI/RKFetchedResultsTableControllerTest.m @@ -25,10 +25,10 @@ - (BOOL)isFooterSection:(NSUInteger)section; - (BOOL)isFooterRow:(NSUInteger)row; - (BOOL)isEmptySection:(NSUInteger)section; - (BOOL)isEmptyRow:(NSUInteger)row; -- (BOOL)isHeaderIndexPath:(NSIndexPath*)indexPath; -- (BOOL)isFooterIndexPath:(NSIndexPath*)indexPath; -- (BOOL)isEmptyItemIndexPath:(NSIndexPath*)indexPath; -- (NSIndexPath*)fetchedResultsIndexPathForIndexPath:(NSIndexPath*)indexPath; +- (BOOL)isHeaderIndexPath:(NSIndexPath *)indexPath; +- (BOOL)isFooterIndexPath:(NSIndexPath *)indexPath; +- (BOOL)isEmptyItemIndexPath:(NSIndexPath *)indexPath; +- (NSIndexPath *)fetchedResultsIndexPathForIndexPath:(NSIndexPath *)indexPath; @end @@ -43,93 +43,99 @@ @interface RKFetchedResultsTableControllerTest : RKTestCase @implementation RKFetchedResultsTableControllerTest -- (void)setUp { +- (void)setUp +{ [RKTestFactory setUp]; - + [[[[UIApplication sharedApplication] windows] objectAtIndex:0] setRootViewController:nil]; } -- (void)tearDown { +- (void)tearDown +{ [RKTestFactory tearDown]; } -- (void)bootstrapStoreAndCache { - RKManagedObjectStore* store = [RKTestFactory managedObjectStore]; - RKManagedObjectMapping* humanMapping = [RKManagedObjectMapping mappingForEntityWithName:@"RKHuman" inManagedObjectStore:store]; +- (void)bootstrapStoreAndCache +{ + RKManagedObjectStore *store = [RKTestFactory managedObjectStore]; + RKManagedObjectMapping *humanMapping = [RKManagedObjectMapping mappingForEntityWithName:@"RKHuman" inManagedObjectStore:store]; [humanMapping mapKeyPath:@"id" toAttribute:@"railsID"]; [humanMapping mapAttributes:@"name", nil]; humanMapping.primaryKeyAttribute = @"railsID"; - + [RKHuman truncateAll]; assertThatInt([RKHuman count:nil], is(equalToInt(0))); - RKHuman* blake = [RKHuman createEntity]; + RKHuman *blake = [RKHuman createEntity]; blake.railsID = [NSNumber numberWithInt:1234]; blake.name = @"blake"; - RKHuman* other = [RKHuman createEntity]; + RKHuman *other = [RKHuman createEntity]; other.railsID = [NSNumber numberWithInt:5678]; other.name = @"other"; - NSError* error = nil; + NSError *error = nil; [store save:&error]; assertThat(error, is(nilValue())); assertThatInt([RKHuman count:nil], is(equalToInt(2))); - - RKObjectManager* objectManager = [RKTestFactory objectManager]; + + RKObjectManager *objectManager = [RKTestFactory objectManager]; [objectManager.mappingProvider setMapping:humanMapping forKeyPath:@"human"]; objectManager.objectStore = store; - + [objectManager.mappingProvider setObjectMapping:humanMapping forResourcePathPattern:@"/JSON/humans/all\\.json" withFetchRequestBlock:^NSFetchRequest *(NSString *resourcePath) { return [RKHuman requestAllSortedBy:@"name" ascending:YES]; }]; } -- (void)bootstrapNakedObjectStoreAndCache { - RKManagedObjectStore* store = [RKTestFactory managedObjectStore]; +- (void)bootstrapNakedObjectStoreAndCache +{ + RKManagedObjectStore *store = [RKTestFactory managedObjectStore]; RKManagedObjectMapping *eventMapping = [RKManagedObjectMapping mappingForClass:[RKEvent class] inManagedObjectStore:store]; [eventMapping mapKeyPath:@"event_id" toAttribute:@"eventID"]; [eventMapping mapKeyPath:@"type" toAttribute:@"eventType"]; [eventMapping mapAttributes:@"location", @"summary", nil]; eventMapping.primaryKeyAttribute = @"eventID"; [RKEvent truncateAll]; - + assertThatInt([RKEvent count:nil], is(equalToInt(0))); RKEvent *nakedEvent = [RKEvent createEntity]; nakedEvent.eventID = @"RK4424"; nakedEvent.eventType = @"Concert"; nakedEvent.location = @"Performance Hall"; nakedEvent.summary = @"Shindig"; - NSError* error = nil; + NSError *error = nil; [store save:&error]; assertThat(error, is(nilValue())); assertThatInt([RKEvent count:nil], is(equalToInt(1))); - - RKObjectManager* objectManager = [RKTestFactory objectManager]; + + RKObjectManager *objectManager = [RKTestFactory objectManager]; [objectManager.mappingProvider addObjectMapping:eventMapping]; objectManager.objectStore = store; - + id mockMappingProvider = [OCMockObject partialMockForObject:objectManager.mappingProvider]; [[[mockMappingProvider stub] andReturn:[RKEvent requestAllSortedBy:@"eventType" ascending:YES]] fetchRequestForResourcePath:@"/JSON/NakedEvents.json"]; } -- (void)bootstrapEmptyStoreAndCache { - RKManagedObjectStore* store = [RKTestFactory managedObjectStore]; - RKManagedObjectMapping* humanMapping = [RKManagedObjectMapping mappingForEntityWithName:@"RKHuman" inManagedObjectStore:store]; +- (void)bootstrapEmptyStoreAndCache +{ + RKManagedObjectStore *store = [RKTestFactory managedObjectStore]; + RKManagedObjectMapping *humanMapping = [RKManagedObjectMapping mappingForEntityWithName:@"RKHuman" inManagedObjectStore:store]; [humanMapping mapKeyPath:@"id" toAttribute:@"railsID"]; [humanMapping mapAttributes:@"name", nil]; humanMapping.primaryKeyAttribute = @"railsID"; - + [RKHuman truncateAll]; assertThatInt([RKHuman count:nil], is(equalToInt(0))); - - RKObjectManager* objectManager = [RKTestFactory objectManager]; + + RKObjectManager *objectManager = [RKTestFactory objectManager]; [objectManager.mappingProvider setMapping:humanMapping forKeyPath:@"human"]; objectManager.objectStore = store; - + id mockMappingProvider = [OCMockObject partialMockForObject:objectManager.mappingProvider]; [[[mockMappingProvider stub] andReturn:[RKHuman requestAllSortedBy:@"name" ascending:YES]] fetchRequestForResourcePath:@"/JSON/humans/all.json"]; [[[mockMappingProvider stub] andReturn:[RKHuman requestAllSortedBy:@"name" ascending:YES]] fetchRequestForResourcePath:@"/empty/array"]; } -- (void)stubObjectManagerToOnline { +- (void)stubObjectManagerToOnline +{ RKObjectManager *objectManager = [RKObjectManager sharedManager]; id mockManager = [OCMockObject partialMockForObject:objectManager]; [mockManager setExpectationOrderMatters:YES]; @@ -139,53 +145,56 @@ - (void)stubObjectManagerToOnline { [[[mockManager stub] andReturnValue:OCMOCK_VALUE(online)] isOnline]; } -- (void)testLoadWithATableViewControllerAndResourcePath { +- (void)testLoadWithATableViewControllerAndResourcePath +{ [self bootstrapStoreAndCache]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = [RKFetchedResultsTableController tableControllerForTableViewController:viewController]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [RKFetchedResultsTableController tableControllerForTableViewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; [tableController loadTable]; - + assertThat(tableController.viewController, is(equalTo(viewController))); assertThat(tableController.tableView, is(equalTo(viewController.tableView))); assertThat(tableController.resourcePath, is(equalTo(@"/JSON/humans/all.json"))); } -- (void)testLoadWithATableViewControllerAndResourcePathFromNakedObjects { +- (void)testLoadWithATableViewControllerAndResourcePathFromNakedObjects +{ [self bootstrapNakedObjectStoreAndCache]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = [RKFetchedResultsTableController tableControllerForTableViewController:viewController]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [RKFetchedResultsTableController tableControllerForTableViewController:viewController]; tableController.resourcePath = @"/JSON/NakedEvents.json"; [tableController setObjectMappingForClass:[RKEvent class]]; [tableController loadTable]; - + assertThat(tableController.viewController, is(equalTo(viewController))); assertThat(tableController.tableView, is(equalTo(viewController.tableView))); assertThat(tableController.resourcePath, is(equalTo(@"/JSON/NakedEvents.json"))); - - RKTableViewCellMapping* cellMapping = [RKTableViewCellMapping mappingForClass:[UITableViewCell class]]; + + RKTableViewCellMapping *cellMapping = [RKTableViewCellMapping mappingForClass:[UITableViewCell class]]; [cellMapping mapKeyPath:@"summary" toAttribute:@"textLabel.text"]; - RKTableViewCellMappings* mappings = [RKTableViewCellMappings new]; + RKTableViewCellMappings *mappings = [RKTableViewCellMappings new]; [mappings setCellMapping:cellMapping forClass:[RKEvent class]]; tableController.cellMappings = mappings; - - UITableViewCell* cell = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; + + UITableViewCell *cell = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; assertThat(cell.textLabel.text, is(equalTo(@"Shindig"))); } -- (void)testLoadWithATableViewControllerAndResourcePathAndPredicateAndSortDescriptors { +- (void)testLoadWithATableViewControllerAndResourcePathAndPredicateAndSortDescriptors +{ [self bootstrapStoreAndCache]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - NSPredicate* predicate = [NSPredicate predicateWithValue:TRUE]; - NSArray* sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"name" + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + NSPredicate *predicate = [NSPredicate predicateWithValue:TRUE]; + NSArray *sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES]]; - RKFetchedResultsTableController* tableController = [RKFetchedResultsTableController tableControllerForTableViewController:viewController]; + RKFetchedResultsTableController *tableController = [RKFetchedResultsTableController tableControllerForTableViewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; tableController.predicate = predicate; tableController.sortDescriptors = sortDescriptors; [tableController loadTable]; - + assertThat(tableController.viewController, is(equalTo(viewController))); assertThat(tableController.resourcePath, is(equalTo(@"/JSON/humans/all.json"))); assertThat(tableController.fetchRequest, is(notNilValue())); @@ -193,15 +202,16 @@ - (void)testLoadWithATableViewControllerAndResourcePathAndPredicateAndSortDescri assertThat([tableController.fetchRequest sortDescriptors], is(equalTo(sortDescriptors))); } -- (void)testLoadWithATableViewControllerAndResourcePathAndSectionNameAndCacheName { +- (void)testLoadWithATableViewControllerAndResourcePathAndSectionNameAndCacheName +{ [self bootstrapStoreAndCache]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = [RKFetchedResultsTableController tableControllerForTableViewController:viewController]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [RKFetchedResultsTableController tableControllerForTableViewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; tableController.sectionNameKeyPath = @"name"; tableController.cacheName = @"allHumansCache"; [tableController loadTable]; - + assertThat(tableController.viewController, is(equalTo(viewController))); assertThat(tableController.resourcePath, is(equalTo(@"/JSON/humans/all.json"))); assertThat(tableController.fetchRequest, is(notNilValue())); @@ -209,20 +219,21 @@ - (void)testLoadWithATableViewControllerAndResourcePathAndSectionNameAndCacheNam assertThat(tableController.fetchedResultsController.cacheName, is(equalTo(@"allHumansCache"))); } -- (void)testLoadWithAllParams { +- (void)testLoadWithAllParams +{ [self bootstrapStoreAndCache]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - NSPredicate* predicate = [NSPredicate predicateWithValue:TRUE]; - NSArray* sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"name" + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + NSPredicate *predicate = [NSPredicate predicateWithValue:TRUE]; + NSArray *sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES]]; - RKFetchedResultsTableController* tableController = [RKFetchedResultsTableController tableControllerForTableViewController:viewController]; + RKFetchedResultsTableController *tableController = [RKFetchedResultsTableController tableControllerForTableViewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; tableController.predicate = predicate; tableController.sortDescriptors = sortDescriptors; tableController.sectionNameKeyPath = @"name"; tableController.cacheName = @"allHumansCache"; [tableController loadTable]; - + assertThat(tableController.viewController, is(equalTo(viewController))); assertThat(tableController.resourcePath, is(equalTo(@"/JSON/humans/all.json"))); assertThat(tableController.fetchRequest, is(notNilValue())); @@ -232,26 +243,28 @@ - (void)testLoadWithAllParams { assertThat(tableController.fetchedResultsController.cacheName, is(equalTo(@"allHumansCache"))); } -- (void)testAlwaysHaveAtLeastOneSection { +- (void)testAlwaysHaveAtLeastOneSection +{ [self bootstrapStoreAndCache]; - UITableView* tableView = [UITableView new]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = + UITableView *tableView = [UITableView new]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:tableView viewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; [tableController loadTable]; - + assertThatInt(tableController.sectionCount, is(equalToInt(1))); } #pragma mark - Section Management -- (void)testProperlyCountSections { +- (void)testProperlyCountSections +{ [self bootstrapStoreAndCache]; - UITableView* tableView = [UITableView new]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = + UITableView *tableView = [UITableView new]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:tableView viewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; @@ -260,11 +273,12 @@ - (void)testProperlyCountSections { assertThatInt(tableController.sectionCount, is(equalToInt(2))); } -- (void)testProperlyCountRows { +- (void)testProperlyCountRows +{ [self bootstrapStoreAndCache]; - UITableView* tableView = [UITableView new]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = + UITableView *tableView = [UITableView new]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:tableView viewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; @@ -272,17 +286,18 @@ - (void)testProperlyCountRows { assertThatInt([tableController rowCount], is(equalToInt(2))); } -- (void)testProperlyCountRowsWithHeaderItems { +- (void)testProperlyCountRowsWithHeaderItems +{ [self bootstrapStoreAndCache]; - UITableView* tableView = [UITableView new]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = + UITableView *tableView = [UITableView new]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:tableView viewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; - [tableController addHeaderRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController addHeaderRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Header"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; @@ -290,17 +305,18 @@ - (void)testProperlyCountRowsWithHeaderItems { assertThatInt([tableController rowCount], is(equalToInt(3))); } -- (void)testProperlyCountRowsWithEmptyItemWhenEmpty { +- (void)testProperlyCountRowsWithEmptyItemWhenEmpty +{ [self bootstrapEmptyStoreAndCache]; - UITableView* tableView = [UITableView new]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = + UITableView *tableView = [UITableView new]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:tableView viewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; - [tableController setEmptyItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController setEmptyItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Empty"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; @@ -308,17 +324,18 @@ - (void)testProperlyCountRowsWithEmptyItemWhenEmpty { assertThatInt([tableController rowCount], is(equalToInt(1))); } -- (void)testProperlyCountRowsWithEmptyItemWhenFull { +- (void)testProperlyCountRowsWithEmptyItemWhenFull +{ [self bootstrapStoreAndCache]; - UITableView* tableView = [UITableView new]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = + UITableView *tableView = [UITableView new]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:tableView viewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; - [tableController setEmptyItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController setEmptyItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Empty"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; @@ -326,24 +343,25 @@ - (void)testProperlyCountRowsWithEmptyItemWhenFull { assertThatInt([tableController rowCount], is(equalToInt(2))); } -- (void)testProperlyCountRowsWithHeaderAndEmptyItemsWhenEmptyDontShowHeaders { +- (void)testProperlyCountRowsWithHeaderAndEmptyItemsWhenEmptyDontShowHeaders +{ [self bootstrapEmptyStoreAndCache]; - UITableView* tableView = [UITableView new]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = + UITableView *tableView = [UITableView new]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:tableView viewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; - [tableController addHeaderRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController addHeaderRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Header"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; tableController.showsHeaderRowsWhenEmpty = NO; - [tableController setEmptyItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController setEmptyItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Empty"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; @@ -351,21 +369,22 @@ - (void)testProperlyCountRowsWithHeaderAndEmptyItemsWhenEmptyDontShowHeaders { assertThatInt([tableController rowCount], is(equalToInt(1))); } -- (void)testProperlyCountRowsWithHeaderAndEmptyItemsWhenEmptyShowHeaders { +- (void)testProperlyCountRowsWithHeaderAndEmptyItemsWhenEmptyShowHeaders +{ [self bootstrapEmptyStoreAndCache]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = [RKFetchedResultsTableController tableControllerForTableViewController:viewController]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [RKFetchedResultsTableController tableControllerForTableViewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; - [tableController addHeaderRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController addHeaderRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Header"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; tableController.showsHeaderRowsWhenEmpty = YES; - [tableController setEmptyItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController setEmptyItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Empty"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; @@ -373,20 +392,21 @@ - (void)testProperlyCountRowsWithHeaderAndEmptyItemsWhenEmptyShowHeaders { assertThatInt([tableController rowCount], is(equalToInt(2))); } -- (void)testProperlyCountRowsWithHeaderAndEmptyItemsWhenFull { +- (void)testProperlyCountRowsWithHeaderAndEmptyItemsWhenFull +{ [self bootstrapStoreAndCache]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = [RKFetchedResultsTableController tableControllerForTableViewController:viewController]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [RKFetchedResultsTableController tableControllerForTableViewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; - [tableController addHeaderRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController addHeaderRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Header"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; - [tableController setEmptyItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController setEmptyItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Empty"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; @@ -396,15 +416,16 @@ - (void)testProperlyCountRowsWithHeaderAndEmptyItemsWhenFull { #pragma mark - UITableViewDataSource specs -- (void)testRaiseAnExceptionIfSentAMessageWithATableViewItIsNotBoundTo { - UITableView* tableView = [UITableView new]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = [RKFetchedResultsTableController tableControllerWithTableView:tableView forViewController:viewController]; - NSException* exception = nil; +- (void)testRaiseAnExceptionIfSentAMessageWithATableViewItIsNotBoundTo +{ + UITableView *tableView = [UITableView new]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [RKFetchedResultsTableController tableControllerWithTableView:tableView forViewController:viewController]; + NSException *exception = nil; @try { [tableController numberOfSectionsInTableView:[UITableView new]]; } - @catch (NSException* e) { + @catch (NSException *e) { exception = e; } @finally { @@ -412,149 +433,156 @@ - (void)testRaiseAnExceptionIfSentAMessageWithATableViewItIsNotBoundTo { } } -- (void)testReturnTheNumberOfSectionsInTableView { +- (void)testReturnTheNumberOfSectionsInTableView +{ [self bootstrapStoreAndCache]; - UITableView* tableView = [UITableView new]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = + UITableView *tableView = [UITableView new]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:tableView viewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; tableController.sectionNameKeyPath = @"name"; [tableController loadTable]; - + assertThatInt([tableController numberOfSectionsInTableView:tableView], is(equalToInt(2))); } -- (void)testReturnTheNumberOfRowsInSectionInTableView { +- (void)testReturnTheNumberOfRowsInSectionInTableView +{ [self bootstrapStoreAndCache]; - UITableView* tableView = [UITableView new]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = + UITableView *tableView = [UITableView new]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:tableView viewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; [tableController loadTable]; - + assertThatInt([tableController tableView:tableView numberOfRowsInSection:0], is(equalToInt(2))); } -- (void)testReturnTheHeaderTitleForSection { +- (void)testReturnTheHeaderTitleForSection +{ [self bootstrapStoreAndCache]; - UITableView* tableView = [UITableView new]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = + UITableView *tableView = [UITableView new]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:tableView viewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; tableController.sectionNameKeyPath = @"name"; [tableController loadTable]; - + assertThat([tableController tableView:tableView titleForHeaderInSection:1], is(equalTo(@"other"))); } -- (void)testReturnTheTableViewCellForRowAtIndexPath { +- (void)testReturnTheTableViewCellForRowAtIndexPath +{ [self bootstrapStoreAndCache]; - UITableView* tableView = [UITableView new]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = + UITableView *tableView = [UITableView new]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:tableView viewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; [tableController loadTable]; - - RKTableViewCellMapping* cellMapping = [RKTableViewCellMapping mappingForClass:[UITableViewCell class]]; + + RKTableViewCellMapping *cellMapping = [RKTableViewCellMapping mappingForClass:[UITableViewCell class]]; [cellMapping mapKeyPath:@"name" toAttribute:@"textLabel.text"]; - RKTableViewCellMappings* mappings = [RKTableViewCellMappings new]; + RKTableViewCellMappings *mappings = [RKTableViewCellMappings new]; [mappings setCellMapping:cellMapping forClass:[RKHuman class]]; tableController.cellMappings = mappings; - - UITableViewCell* cell = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; + + UITableViewCell *cell = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; assertThat(cell.textLabel.text, is(equalTo(@"blake"))); } #pragma mark - Table Cell Mapping -- (void)testReturnTheObjectForARowAtIndexPath { +- (void)testReturnTheObjectForARowAtIndexPath +{ [self bootstrapStoreAndCache]; - UITableView* tableView = [UITableView new]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = + UITableView *tableView = [UITableView new]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:tableView viewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; [tableController loadTable]; - - NSIndexPath* indexPath = [NSIndexPath indexPathForRow:0 inSection:0]; - RKHuman* blake = [RKHuman findFirstByAttribute:@"name" withValue:@"blake"]; + + NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0]; + RKHuman *blake = [RKHuman findFirstByAttribute:@"name" withValue:@"blake"]; assertThatBool(blake == [tableController objectForRowAtIndexPath:indexPath], is(equalToBool(YES))); [tableController release]; } #pragma mark - Editing -- (void)testFireADeleteRequestWhenTheCanEditRowsPropertyIsSet { +- (void)testFireADeleteRequestWhenTheCanEditRowsPropertyIsSet +{ [self bootstrapStoreAndCache]; [self stubObjectManagerToOnline]; [[RKObjectManager sharedManager].router routeClass:[RKHuman class] toResourcePath:@"/humans/:railsID" forMethod:RKRequestMethodDELETE]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = [RKFetchedResultsTableController tableControllerForTableViewController:viewController]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [RKFetchedResultsTableController tableControllerForTableViewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; tableController.canEditRows = YES; RKTableViewCellMapping *cellMapping = [RKTableViewCellMapping cellMapping]; [cellMapping mapKeyPath:@"name" toAttribute:@"textLabel.text"]; [tableController mapObjectsWithClass:[RKHuman class] toTableCellsWithMapping:cellMapping]; [tableController loadTable]; - - NSIndexPath* indexPath = [NSIndexPath indexPathForRow:1 inSection:0]; - NSIndexPath* deleteIndexPath = [NSIndexPath indexPathForRow:0 inSection:0]; - RKHuman* blake = [RKHuman findFirstByAttribute:@"name" withValue:@"blake"]; - RKHuman* other = [RKHuman findFirstByAttribute:@"name" withValue:@"other"]; - + + NSIndexPath *indexPath = [NSIndexPath indexPathForRow:1 inSection:0]; + NSIndexPath *deleteIndexPath = [NSIndexPath indexPathForRow:0 inSection:0]; + RKHuman *blake = [RKHuman findFirstByAttribute:@"name" withValue:@"blake"]; + RKHuman *other = [RKHuman findFirstByAttribute:@"name" withValue:@"other"]; + assertThatInt([tableController rowCount], is(equalToInt(2))); assertThat([tableController objectForRowAtIndexPath:indexPath], is(equalTo(other))); assertThat([tableController objectForRowAtIndexPath:deleteIndexPath], is(equalTo(blake))); BOOL delegateCanEdit = [tableController tableView:tableController.tableView canEditRowAtIndexPath:deleteIndexPath]; assertThatBool(delegateCanEdit, is(equalToBool(YES))); - + [RKTestNotificationObserver waitForNotificationWithName:RKRequestDidLoadResponseNotification usingBlock:^{ [tableController tableView:tableController.tableView commitEditingStyle:UITableViewCellEditingStyleDelete forRowAtIndexPath:deleteIndexPath]; }]; - + assertThatInt([tableController rowCount], is(equalToInt(1))); assertThat([tableController objectForRowAtIndexPath:deleteIndexPath], is(equalTo(other))); assertThatBool([blake isDeleted], is(equalToBool(YES))); } -- (void)testLocallyCommitADeleteWhenTheCanEditRowsPropertyIsSet { +- (void)testLocallyCommitADeleteWhenTheCanEditRowsPropertyIsSet +{ [self bootstrapStoreAndCache]; [self stubObjectManagerToOnline]; - - UITableView* tableView = [UITableView new]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = + + UITableView *tableView = [UITableView new]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:tableView viewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; tableController.canEditRows = YES; [tableController loadTable]; - - NSIndexPath* indexPath = [NSIndexPath indexPathForRow:0 inSection:0]; - NSIndexPath* deleteIndexPath = [NSIndexPath indexPathForRow:1 inSection:0]; - RKHuman* blake = [RKHuman findFirstByAttribute:@"name" withValue:@"blake"]; - RKHuman* other = [RKHuman findFirstByAttribute:@"name" withValue:@"other"]; + + NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0]; + NSIndexPath *deleteIndexPath = [NSIndexPath indexPathForRow:1 inSection:0]; + RKHuman *blake = [RKHuman findFirstByAttribute:@"name" withValue:@"blake"]; + RKHuman *other = [RKHuman findFirstByAttribute:@"name" withValue:@"other"]; blake.railsID = nil; other.railsID = nil; - - NSError* error = nil; + + NSError *error = nil; [blake.managedObjectContext save:&error]; assertThat(error, is(nilValue())); - + assertThatInt([tableController rowCount], is(equalToInt(2))); assertThat([tableController objectForRowAtIndexPath:indexPath], is(equalTo(blake))); assertThat([tableController objectForRowAtIndexPath:deleteIndexPath], is(equalTo(other))); @@ -568,22 +596,23 @@ - (void)testLocallyCommitADeleteWhenTheCanEditRowsPropertyIsSet { assertThat([tableController objectForRowAtIndexPath:indexPath], is(equalTo(blake))); } -- (void)testNotCommitADeletionWhenTheCanEditRowsPropertyIsNotSet { +- (void)testNotCommitADeletionWhenTheCanEditRowsPropertyIsNotSet +{ [self bootstrapStoreAndCache]; [self stubObjectManagerToOnline]; - - UITableView* tableView = [UITableView new]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = + + UITableView *tableView = [UITableView new]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:tableView viewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; [tableController loadTable]; - - NSIndexPath* indexPath = [NSIndexPath indexPathForRow:0 inSection:0]; - RKHuman* blake = [RKHuman findFirstByAttribute:@"name" withValue:@"blake"]; - RKHuman* other = [RKHuman findFirstByAttribute:@"name" withValue:@"other"]; - + + NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0]; + RKHuman *blake = [RKHuman findFirstByAttribute:@"name" withValue:@"blake"]; + RKHuman *other = [RKHuman findFirstByAttribute:@"name" withValue:@"other"]; + assertThatInt([tableController rowCount], is(equalToInt(2))); BOOL delegateCanEdit = [tableController tableView:tableController.tableView canEditRowAtIndexPath:indexPath]; @@ -597,23 +626,24 @@ - (void)testNotCommitADeletionWhenTheCanEditRowsPropertyIsNotSet { is(equalTo(other))); } -- (void)testDoNothingToCommitAnInsertionWhenTheCanEditRowsPropertyIsSet { +- (void)testDoNothingToCommitAnInsertionWhenTheCanEditRowsPropertyIsSet +{ [self bootstrapStoreAndCache]; [self stubObjectManagerToOnline]; - - UITableView* tableView = [UITableView new]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = + + UITableView *tableView = [UITableView new]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:tableView viewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; tableController.canEditRows = YES; [tableController loadTable]; - - NSIndexPath* indexPath = [NSIndexPath indexPathForRow:0 inSection:0]; - RKHuman* blake = [RKHuman findFirstByAttribute:@"name" withValue:@"blake"]; - RKHuman* other = [RKHuman findFirstByAttribute:@"name" withValue:@"other"]; - + + NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0]; + RKHuman *blake = [RKHuman findFirstByAttribute:@"name" withValue:@"blake"]; + RKHuman *other = [RKHuman findFirstByAttribute:@"name" withValue:@"other"]; + assertThatInt([tableController rowCount], is(equalToInt(2))); BOOL delegateCanEdit = [tableController tableView:tableController.tableView canEditRowAtIndexPath:indexPath]; @@ -627,21 +657,22 @@ - (void)testDoNothingToCommitAnInsertionWhenTheCanEditRowsPropertyIsSet { is(equalTo(other))); } -- (void)testNotMoveARowWhenTheCanMoveRowsPropertyIsSet { +- (void)testNotMoveARowWhenTheCanMoveRowsPropertyIsSet +{ [self bootstrapStoreAndCache]; - UITableView* tableView = [UITableView new]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = + UITableView *tableView = [UITableView new]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:tableView viewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; tableController.canMoveRows = YES; [tableController loadTable]; - - NSIndexPath* indexPath = [NSIndexPath indexPathForRow:0 inSection:0]; - RKHuman* blake = [RKHuman findFirstByAttribute:@"name" withValue:@"blake"]; - RKHuman* other = [RKHuman findFirstByAttribute:@"name" withValue:@"other"]; - + + NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0]; + RKHuman *blake = [RKHuman findFirstByAttribute:@"name" withValue:@"blake"]; + RKHuman *other = [RKHuman findFirstByAttribute:@"name" withValue:@"other"]; + assertThatInt([tableController rowCount], is(equalToInt(2))); BOOL delegateCanMove = [tableController tableView:tableController.tableView canMoveRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; @@ -657,11 +688,12 @@ - (void)testNotMoveARowWhenTheCanMoveRowsPropertyIsSet { #pragma mark - Header, Footer, and Empty Rows -- (void)testDetermineIfASectionIndexIsAHeaderSection { +- (void)testDetermineIfASectionIndexIsAHeaderSection +{ [self bootstrapEmptyStoreAndCache]; - UITableView* tableView = [UITableView new]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = + UITableView *tableView = [UITableView new]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:tableView viewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; @@ -671,17 +703,18 @@ - (void)testDetermineIfASectionIndexIsAHeaderSection { assertThatBool([tableController isHeaderSection:2], is(equalToBool(NO))); } -- (void)testDetermineIfARowIndexIsAHeaderRow { +- (void)testDetermineIfARowIndexIsAHeaderRow +{ [self bootstrapStoreAndCache]; - UITableView* tableView = [UITableView new]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = + UITableView *tableView = [UITableView new]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:tableView viewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; - [tableController addHeaderRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController addHeaderRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Header"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; @@ -691,17 +724,18 @@ - (void)testDetermineIfARowIndexIsAHeaderRow { assertThatBool([tableController isHeaderRow:2], is(equalToBool(NO))); } -- (void)testDetermineIfASectionIndexIsAFooterSectionSingleSection { +- (void)testDetermineIfASectionIndexIsAFooterSectionSingleSection +{ [self bootstrapStoreAndCache]; - UITableView* tableView = [UITableView new]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = + UITableView *tableView = [UITableView new]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:tableView viewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; - [tableController addFooterRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController addFooterRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Footer"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; @@ -711,18 +745,19 @@ - (void)testDetermineIfASectionIndexIsAFooterSectionSingleSection { assertThatBool([tableController isFooterSection:2], is(equalToBool(NO))); } -- (void)testDetermineIfASectionIndexIsAFooterSectionMultipleSections { +- (void)testDetermineIfASectionIndexIsAFooterSectionMultipleSections +{ [self bootstrapStoreAndCache]; - UITableView* tableView = [UITableView new]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = + UITableView *tableView = [UITableView new]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:tableView viewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; tableController.sectionNameKeyPath = @"name"; - [tableController addFooterRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController addFooterRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Footer"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; @@ -732,17 +767,18 @@ - (void)testDetermineIfASectionIndexIsAFooterSectionMultipleSections { assertThatBool([tableController isFooterSection:2], is(equalToBool(NO))); } -- (void)testDetermineIfARowIndexIsAFooterRow { +- (void)testDetermineIfARowIndexIsAFooterRow +{ [self bootstrapStoreAndCache]; - UITableView* tableView = [UITableView new]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = + UITableView *tableView = [UITableView new]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:tableView viewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; - [tableController addFooterRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController addFooterRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Footer"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; @@ -752,11 +788,12 @@ - (void)testDetermineIfARowIndexIsAFooterRow { assertThatBool([tableController isFooterRow:2], is(equalToBool(YES))); } -- (void)testDetermineIfASectionIndexIsAnEmptySection { +- (void)testDetermineIfASectionIndexIsAnEmptySection +{ [self bootstrapEmptyStoreAndCache]; - UITableView* tableView = [UITableView new]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = + UITableView *tableView = [UITableView new]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:tableView viewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; @@ -766,11 +803,12 @@ - (void)testDetermineIfASectionIndexIsAnEmptySection { assertThatBool([tableController isEmptySection:2], is(equalToBool(NO))); } -- (void)testDetermineIfARowIndexIsAnEmptyRow { +- (void)testDetermineIfARowIndexIsAnEmptyRow +{ [self bootstrapEmptyStoreAndCache]; - UITableView* tableView = [UITableView new]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = + UITableView *tableView = [UITableView new]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:tableView viewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; @@ -780,17 +818,18 @@ - (void)testDetermineIfARowIndexIsAnEmptyRow { assertThatBool([tableController isEmptyRow:2], is(equalToBool(NO))); } -- (void)testDetermineIfAnIndexPathIsAHeaderIndexPath { +- (void)testDetermineIfAnIndexPathIsAHeaderIndexPath +{ [self bootstrapStoreAndCache]; - UITableView* tableView = [UITableView new]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = + UITableView *tableView = [UITableView new]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:tableView viewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; - [tableController addHeaderRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController addHeaderRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Header"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; @@ -803,17 +842,18 @@ - (void)testDetermineIfAnIndexPathIsAHeaderIndexPath { assertThatBool([tableController isHeaderIndexPath:[NSIndexPath indexPathForRow:2 inSection:1]], is(equalToBool(NO))); } -- (void)testDetermineIfAnIndexPathIsAFooterIndexPath { +- (void)testDetermineIfAnIndexPathIsAFooterIndexPath +{ [self bootstrapStoreAndCache]; - UITableView* tableView = [UITableView new]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = + UITableView *tableView = [UITableView new]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:tableView viewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; - [tableController addFooterRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController addFooterRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Footer"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; @@ -826,17 +866,18 @@ - (void)testDetermineIfAnIndexPathIsAFooterIndexPath { assertThatBool([tableController isFooterIndexPath:[NSIndexPath indexPathForRow:2 inSection:1]], is(equalToBool(NO))); } -- (void)testDetermineIfAnIndexPathIsAnEmptyIndexPathSingleSectionEmptyItemOnly { +- (void)testDetermineIfAnIndexPathIsAnEmptyIndexPathSingleSectionEmptyItemOnly +{ [self bootstrapEmptyStoreAndCache]; - UITableView* tableView = [UITableView new]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = + UITableView *tableView = [UITableView new]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:tableView viewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; - [tableController setEmptyItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController setEmptyItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Empty"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; @@ -849,17 +890,18 @@ - (void)testDetermineIfAnIndexPathIsAnEmptyIndexPathSingleSectionEmptyItemOnly { assertThatBool([tableController isEmptyItemIndexPath:[NSIndexPath indexPathForRow:2 inSection:1]], is(equalToBool(NO))); } -- (void)testConvertAnIndexPathForHeaderRows { +- (void)testConvertAnIndexPathForHeaderRows +{ [self bootstrapStoreAndCache]; - UITableView* tableView = [UITableView new]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = + UITableView *tableView = [UITableView new]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:tableView viewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; - [tableController addHeaderRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController addHeaderRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Header"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; @@ -870,17 +912,18 @@ - (void)testConvertAnIndexPathForHeaderRows { assertThat([tableController fetchedResultsIndexPathForIndexPath:[NSIndexPath indexPathForRow:3 inSection:0]], is(equalTo([NSIndexPath indexPathForRow:2 inSection:0]))); } -- (void)testConvertAnIndexPathForFooterRowsSingleSection { +- (void)testConvertAnIndexPathForFooterRowsSingleSection +{ [self bootstrapStoreAndCache]; - UITableView* tableView = [UITableView new]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = + UITableView *tableView = [UITableView new]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:tableView viewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; - [tableController addFooterRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController addFooterRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Footer"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; @@ -890,18 +933,19 @@ - (void)testConvertAnIndexPathForFooterRowsSingleSection { assertThat([tableController fetchedResultsIndexPathForIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]], is(equalTo([NSIndexPath indexPathForRow:2 inSection:0]))); } -- (void)testConvertAnIndexPathForFooterRowsMultipleSections { +- (void)testConvertAnIndexPathForFooterRowsMultipleSections +{ [self bootstrapStoreAndCache]; - UITableView* tableView = [UITableView new]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = + UITableView *tableView = [UITableView new]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:tableView viewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; tableController.sectionNameKeyPath = @"name"; - [tableController addFooterRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController addFooterRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Footer"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; @@ -912,17 +956,18 @@ - (void)testConvertAnIndexPathForFooterRowsMultipleSections { assertThat([tableController fetchedResultsIndexPathForIndexPath:[NSIndexPath indexPathForRow:1 inSection:1]], is(equalTo([NSIndexPath indexPathForRow:1 inSection:1]))); } -- (void)testConvertAnIndexPathForEmptyRow { +- (void)testConvertAnIndexPathForEmptyRow +{ [self bootstrapStoreAndCache]; - UITableView* tableView = [UITableView new]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = + UITableView *tableView = [UITableView new]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:tableView viewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; - [tableController setEmptyItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController setEmptyItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Empty"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; @@ -933,23 +978,24 @@ - (void)testConvertAnIndexPathForEmptyRow { assertThat([tableController fetchedResultsIndexPathForIndexPath:[NSIndexPath indexPathForRow:3 inSection:0]], is(equalTo([NSIndexPath indexPathForRow:3 inSection:0]))); } -- (void)testConvertAnIndexPathForHeaderFooterRowsSingleSection { +- (void)testConvertAnIndexPathForHeaderFooterRowsSingleSection +{ [self bootstrapStoreAndCache]; - UITableView* tableView = [UITableView new]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = + UITableView *tableView = [UITableView new]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:tableView viewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; - [tableController addHeaderRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController addHeaderRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Header"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; - [tableController addFooterRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController addFooterRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Footer"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; @@ -960,24 +1006,25 @@ - (void)testConvertAnIndexPathForHeaderFooterRowsSingleSection { assertThat([tableController fetchedResultsIndexPathForIndexPath:[NSIndexPath indexPathForRow:3 inSection:0]], is(equalTo([NSIndexPath indexPathForRow:2 inSection:0]))); } -- (void)testConvertAnIndexPathForHeaderFooterRowsMultipleSections { +- (void)testConvertAnIndexPathForHeaderFooterRowsMultipleSections +{ [self bootstrapStoreAndCache]; - UITableView* tableView = [UITableView new]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = + UITableView *tableView = [UITableView new]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:tableView viewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; tableController.sectionNameKeyPath = @"name"; - [tableController addHeaderRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController addHeaderRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Header"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; - [tableController addFooterRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController addFooterRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Footer"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; @@ -989,29 +1036,30 @@ - (void)testConvertAnIndexPathForHeaderFooterRowsMultipleSections { assertThat([tableController fetchedResultsIndexPathForIndexPath:[NSIndexPath indexPathForRow:2 inSection:1]], is(equalTo([NSIndexPath indexPathForRow:2 inSection:1]))); } -- (void)testConvertAnIndexPathForHeaderFooterEmptyRowsSingleSection { +- (void)testConvertAnIndexPathForHeaderFooterEmptyRowsSingleSection +{ [self bootstrapStoreAndCache]; - UITableView* tableView = [UITableView new]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = + UITableView *tableView = [UITableView new]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:tableView viewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; - [tableController addHeaderRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController addHeaderRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Header"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; - [tableController addFooterRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController addFooterRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Footer"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; - [tableController setEmptyItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController setEmptyItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Empty"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; @@ -1023,30 +1071,31 @@ - (void)testConvertAnIndexPathForHeaderFooterEmptyRowsSingleSection { assertThat([tableController fetchedResultsIndexPathForIndexPath:[NSIndexPath indexPathForRow:5 inSection:0]], is(equalTo([NSIndexPath indexPathForRow:4 inSection:0]))); } -- (void)testConvertAnIndexPathForHeaderFooterEmptyRowsMultipleSections { +- (void)testConvertAnIndexPathForHeaderFooterEmptyRowsMultipleSections +{ [self bootstrapStoreAndCache]; - UITableView* tableView = [UITableView new]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = + UITableView *tableView = [UITableView new]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:tableView viewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; tableController.sectionNameKeyPath = @"name"; - [tableController addHeaderRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController addHeaderRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Header"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; - [tableController addFooterRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController addFooterRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Footer"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; - [tableController setEmptyItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController setEmptyItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Empty"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; @@ -1057,23 +1106,24 @@ - (void)testConvertAnIndexPathForHeaderFooterEmptyRowsMultipleSections { assertThat([tableController fetchedResultsIndexPathForIndexPath:[NSIndexPath indexPathForRow:2 inSection:1]], is(equalTo([NSIndexPath indexPathForRow:2 inSection:1]))); } -- (void)testConvertAnIndexPathForHeaderEmptyRows { +- (void)testConvertAnIndexPathForHeaderEmptyRows +{ [self bootstrapStoreAndCache]; - UITableView* tableView = [UITableView new]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = + UITableView *tableView = [UITableView new]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:tableView viewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; - [tableController addHeaderRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController addHeaderRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Header"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; - [tableController setEmptyItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController setEmptyItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Empty"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; @@ -1083,17 +1133,18 @@ - (void)testConvertAnIndexPathForHeaderEmptyRows { assertThat([tableController fetchedResultsIndexPathForIndexPath:[NSIndexPath indexPathForRow:3 inSection:0]], is(equalTo([NSIndexPath indexPathForRow:2 inSection:0]))); } -- (void)testShowHeaderRows { +- (void)testShowHeaderRows +{ [self bootstrapStoreAndCache]; - UITableView* tableView = [UITableView new]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = + UITableView *tableView = [UITableView new]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:tableView viewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; - RKTableItem* headerRow = [RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + RKTableItem *headerRow = [RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Header"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]; @@ -1101,10 +1152,10 @@ - (void)testShowHeaderRows { tableController.showsHeaderRowsWhenEmpty = NO; tableController.showsFooterRowsWhenEmpty = NO; [tableController loadTable]; - - RKHuman* blake = [RKHuman findFirstByAttribute:@"name" withValue:@"blake"]; - RKHuman* other = [RKHuman findFirstByAttribute:@"name" withValue:@"other"]; - + + RKHuman *blake = [RKHuman findFirstByAttribute:@"name" withValue:@"blake"]; + RKHuman *other = [RKHuman findFirstByAttribute:@"name" withValue:@"other"]; + assertThatInt([tableController rowCount], is(equalToInt(3))); assertThat([tableController objectForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]], is(equalTo(headerRow))); assertThat([tableController objectForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]], is(equalTo(blake))); @@ -1112,17 +1163,18 @@ - (void)testShowHeaderRows { is(equalTo(other))); } -- (void)testShowFooterRows { +- (void)testShowFooterRows +{ [self bootstrapStoreAndCache]; - UITableView* tableView = [UITableView new]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = + UITableView *tableView = [UITableView new]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:tableView viewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; - RKTableItem* footerRow = [RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + RKTableItem *footerRow = [RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Footer"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]; @@ -1130,10 +1182,10 @@ - (void)testShowFooterRows { tableController.showsHeaderRowsWhenEmpty = NO; tableController.showsFooterRowsWhenEmpty = NO; [tableController loadTable]; - - RKHuman* blake = [RKHuman findFirstByAttribute:@"name" withValue:@"blake"]; - RKHuman* other = [RKHuman findFirstByAttribute:@"name" withValue:@"other"]; - + + RKHuman *blake = [RKHuman findFirstByAttribute:@"name" withValue:@"blake"]; + RKHuman *other = [RKHuman findFirstByAttribute:@"name" withValue:@"other"]; + assertThatInt([tableController rowCount], is(equalToInt(3))); assertThat([tableController objectForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]], is(equalTo(blake))); assertThat([tableController objectForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]], is(equalTo(other))); @@ -1141,115 +1193,119 @@ - (void)testShowFooterRows { is(equalTo(footerRow))); } -- (void)testHideHeaderRowsWhenEmptyWhenPropertyIsNotSet { +- (void)testHideHeaderRowsWhenEmptyWhenPropertyIsNotSet +{ [self bootstrapEmptyStoreAndCache]; - UITableView* tableView = [UITableView new]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = + UITableView *tableView = [UITableView new]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:tableView viewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; - [tableController addHeaderRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController addHeaderRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Header"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; tableController.showsHeaderRowsWhenEmpty = NO; tableController.showsFooterRowsWhenEmpty = NO; [tableController loadTable]; - + assertThatBool(tableController.isLoaded, is(equalToBool(YES))); assertThatInt([tableController rowCount], is(equalToInt(0))); assertThatBool(tableController.isEmpty, is(equalToBool(YES))); } -- (void)testHideFooterRowsWhenEmptyWhenPropertyIsNotSet { +- (void)testHideFooterRowsWhenEmptyWhenPropertyIsNotSet +{ [self bootstrapEmptyStoreAndCache]; - UITableView* tableView = [UITableView new]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = + UITableView *tableView = [UITableView new]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:tableView viewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; - [tableController addFooterRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController addFooterRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Footer"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; tableController.showsHeaderRowsWhenEmpty = NO; tableController.showsFooterRowsWhenEmpty = NO; [tableController loadTable]; - + assertThatBool(tableController.isLoaded, is(equalToBool(YES))); assertThatInt([tableController rowCount], is(equalToInt(0))); assertThatBool(tableController.isEmpty, is(equalToBool(YES))); } -- (void)testRemoveHeaderAndFooterCountsWhenDeterminingIsEmpty { +- (void)testRemoveHeaderAndFooterCountsWhenDeterminingIsEmpty +{ [self bootstrapEmptyStoreAndCache]; - UITableView* tableView = [UITableView new]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = + UITableView *tableView = [UITableView new]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:tableView viewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; - [tableController addHeaderRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController addHeaderRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Header"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; - [tableController addFooterRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController addFooterRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Footer"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; - [tableController setEmptyItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController setEmptyItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Empty"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; tableController.showsHeaderRowsWhenEmpty = NO; tableController.showsFooterRowsWhenEmpty = NO; [tableController loadTable]; - + assertThatBool(tableController.isLoaded, is(equalToBool(YES))); assertThatInt([tableController rowCount], is(equalToInt(1))); assertThatBool(tableController.isEmpty, is(equalToBool(YES))); } -- (void)testNotShowTheEmptyItemWhenTheTableIsNotEmpty { +- (void)testNotShowTheEmptyItemWhenTheTableIsNotEmpty +{ [self bootstrapStoreAndCache]; - UITableView* tableView = [UITableView new]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = + UITableView *tableView = [UITableView new]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:tableView viewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; - - RKTableItem* headerRow = [RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + + RKTableItem *headerRow = [RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Header"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]; [tableController addHeaderRowForItem:headerRow]; - - RKTableItem* footerRow = [RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + + RKTableItem *footerRow = [RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Footer"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]; [tableController addFooterRowForItem:footerRow]; - - RKTableItem* emptyItem = [RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + + RKTableItem *emptyItem = [RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Empty"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]; @@ -1257,10 +1313,10 @@ - (void)testNotShowTheEmptyItemWhenTheTableIsNotEmpty { tableController.showsHeaderRowsWhenEmpty = NO; tableController.showsFooterRowsWhenEmpty = NO; [tableController loadTable]; - - RKHuman* blake = [RKHuman findFirstByAttribute:@"name" withValue:@"blake"]; - RKHuman* other = [RKHuman findFirstByAttribute:@"name" withValue:@"other"]; - + + RKHuman *blake = [RKHuman findFirstByAttribute:@"name" withValue:@"blake"]; + RKHuman *other = [RKHuman findFirstByAttribute:@"name" withValue:@"other"]; + assertThatInt([tableController rowCount], is(equalToInt(4))); assertThat([tableController objectForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]], is(equalTo(headerRow))); assertThat([tableController objectForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]], is(equalTo(blake))); @@ -1269,93 +1325,96 @@ - (void)testNotShowTheEmptyItemWhenTheTableIsNotEmpty { is(equalTo(footerRow))); } -- (void)testShowTheEmptyItemWhenTheTableIsEmpty { +- (void)testShowTheEmptyItemWhenTheTableIsEmpty +{ [self bootstrapEmptyStoreAndCache]; - UITableView* tableView = [UITableView new]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = + UITableView *tableView = [UITableView new]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:tableView viewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; - [tableController addHeaderRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController addHeaderRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Header"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; - [tableController addFooterRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController addFooterRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Footer"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; - [tableController setEmptyItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController setEmptyItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Empty"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; tableController.showsHeaderRowsWhenEmpty = NO; tableController.showsFooterRowsWhenEmpty = NO; [tableController loadTable]; - + assertThatBool(tableController.isLoaded, is(equalToBool(YES))); assertThatInt([tableController rowCount], is(equalToInt(1))); assertThatBool(tableController.isEmpty, is(equalToBool(YES))); } -- (void)testShowTheEmptyItemPlusHeadersAndFootersWhenTheTableIsEmpty { +- (void)testShowTheEmptyItemPlusHeadersAndFootersWhenTheTableIsEmpty +{ [self bootstrapEmptyStoreAndCache]; - UITableView* tableView = [UITableView new]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = + UITableView *tableView = [UITableView new]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:tableView viewController:viewController]; tableController.resourcePath = @"/JSON/humans/all.json"; - [tableController addHeaderRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController addHeaderRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Header"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; - [tableController addFooterRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController addFooterRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Footer"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; - [tableController setEmptyItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController setEmptyItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Empty"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; tableController.showsHeaderRowsWhenEmpty = YES; tableController.showsFooterRowsWhenEmpty = YES; [tableController loadTable]; - + assertThatBool(tableController.isLoaded, is(equalToBool(YES))); assertThatInt([tableController rowCount], is(equalToInt(3))); assertThatBool(tableController.isEmpty, is(equalToBool(YES))); } -- (void)testShowTheEmptyImageAfterLoadingAnEmptyCollectionIntoAnEmptyFetch { +- (void)testShowTheEmptyImageAfterLoadingAnEmptyCollectionIntoAnEmptyFetch +{ [self bootstrapEmptyStoreAndCache]; [self stubObjectManagerToOnline]; - - UITableView* tableView = [UITableView new]; - - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = [[RKFetchedResultsTableController alloc] initWithTableView:tableView + + UITableView *tableView = [UITableView new]; + + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:tableView viewController:viewController]; - + UIImage *image = [RKTestFixture imageWithContentsOfFixture:@"blake.png"]; - + tableController.imageForEmpty = image; tableController.resourcePath = @"/empty/array"; tableController.autoRefreshFromNetwork = YES; [tableController.cache invalidateAll]; - + [RKTestNotificationObserver waitForNotificationWithName:RKTableControllerDidFinishLoadNotification usingBlock:^{ [tableController loadTable]; }]; @@ -1365,16 +1424,17 @@ - (void)testShowTheEmptyImageAfterLoadingAnEmptyCollectionIntoAnEmptyFetch { assertThat(tableController.stateOverlayImageView.image, is(notNilValue())); } -- (void)testPostANotificationWhenObjectsAreLoaded { +- (void)testPostANotificationWhenObjectsAreLoaded +{ [self bootstrapNakedObjectStoreAndCache]; - UITableView* tableView = [UITableView new]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = + UITableView *tableView = [UITableView new]; + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:tableView viewController:viewController]; tableController.resourcePath = @"/JSON/NakedEvents.json"; - [tableController setObjectMappingForClass:[RKEvent class]]; - + [tableController setObjectMappingForClass:[RKEvent class]]; + id observerMock = [OCMockObject observerMock]; [[NSNotificationCenter defaultCenter] addMockObserver:observerMock name:RKTableControllerDidLoadObjectsNotification object:tableController]; [[observerMock expect] notificationWithName:RKTableControllerDidLoadObjectsNotification object:tableController]; @@ -1384,17 +1444,18 @@ - (void)testPostANotificationWhenObjectsAreLoaded { #pragma mark - Delegate Methods -- (void)testDelegateIsInformedOnInsertSection { +- (void)testDelegateIsInformedOnInsertSection +{ [self bootstrapStoreAndCache]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:viewController.tableView viewController:viewController]; RKTableViewCellMapping *cellMapping = [RKTableViewCellMapping cellMapping]; [cellMapping mapKeyPath:@"name" toAttribute:@"textLabel.text"]; [tableController mapObjectsWithClass:[RKHuman class] toTableCellsWithMapping:cellMapping]; tableController.resourcePath = @"/JSON/humans/all.json"; tableController.cacheName = @"allHumansCache"; - + RKFetchedResultsTableControllerTestDelegate *delegate = [RKFetchedResultsTableControllerTestDelegate tableControllerDelegate]; id mockDelegate = [OCMockObject partialMockForObject:delegate]; [[mockDelegate expect] tableController:tableController didInsertSectionAtIndex:0]; @@ -1406,17 +1467,18 @@ - (void)testDelegateIsInformedOnInsertSection { [mockDelegate verify]; } -- (void)testDelegateIsInformedOfDidStartLoad { +- (void)testDelegateIsInformedOfDidStartLoad +{ [self bootstrapStoreAndCache]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:viewController.tableView viewController:viewController]; RKTableViewCellMapping *cellMapping = [RKTableViewCellMapping cellMapping]; [cellMapping mapKeyPath:@"name" toAttribute:@"textLabel.text"]; [tableController mapObjectsWithClass:[RKHuman class] toTableCellsWithMapping:cellMapping]; tableController.resourcePath = @"/JSON/humans/all.json"; tableController.cacheName = @"allHumansCache"; - + id mockDelegate = [OCMockObject niceMockForProtocol:@protocol(RKFetchedResultsTableControllerDelegate)]; [[mockDelegate expect] tableControllerDidStartLoad:tableController]; tableController.delegate = mockDelegate; @@ -1425,17 +1487,18 @@ - (void)testDelegateIsInformedOfDidStartLoad { [mockDelegate verify]; } -- (void)testDelegateIsInformedOfDidFinishLoad { +- (void)testDelegateIsInformedOfDidFinishLoad +{ [self bootstrapStoreAndCache]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:viewController.tableView viewController:viewController]; RKTableViewCellMapping *cellMapping = [RKTableViewCellMapping cellMapping]; [cellMapping mapKeyPath:@"name" toAttribute:@"textLabel.text"]; [tableController mapObjectsWithClass:[RKHuman class] toTableCellsWithMapping:cellMapping]; tableController.resourcePath = @"/JSON/humans/all.json"; tableController.cacheName = @"allHumansCache"; - + id mockDelegate = [OCMockObject niceMockForProtocol:@protocol(RKFetchedResultsTableControllerDelegate)]; [[mockDelegate expect] tableControllerDidFinishLoad:tableController]; tableController.delegate = mockDelegate; @@ -1444,17 +1507,18 @@ - (void)testDelegateIsInformedOfDidFinishLoad { [mockDelegate verify]; } -- (void)testDelegateIsInformedOfDidInsertObjectAtIndexPath { +- (void)testDelegateIsInformedOfDidInsertObjectAtIndexPath +{ [self bootstrapStoreAndCache]; - RKFetchedResultsTableControllerSpecViewController* viewController = [RKFetchedResultsTableControllerSpecViewController new]; - RKFetchedResultsTableController* tableController = + RKFetchedResultsTableControllerSpecViewController *viewController = [RKFetchedResultsTableControllerSpecViewController new]; + RKFetchedResultsTableController *tableController = [[RKFetchedResultsTableController alloc] initWithTableView:viewController.tableView viewController:viewController]; RKTableViewCellMapping *cellMapping = [RKTableViewCellMapping cellMapping]; [cellMapping mapKeyPath:@"name" toAttribute:@"textLabel.text"]; [tableController mapObjectsWithClass:[RKHuman class] toTableCellsWithMapping:cellMapping]; tableController.resourcePath = @"/JSON/humans/all.json"; tableController.cacheName = @"allHumansCache"; - + id mockDelegate = [OCMockObject niceMockForProtocol:@protocol(RKFetchedResultsTableControllerDelegate)]; [[mockDelegate expect] tableController:tableController didInsertObject:OCMOCK_ANY atIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; [[mockDelegate expect] tableController:tableController didInsertObject:OCMOCK_ANY atIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]]; diff --git a/Tests/Application/UI/RKFormTest.m b/Tests/Application/UI/RKFormTest.m index d5554e779a..d946e94ecd 100644 --- a/Tests/Application/UI/RKFormTest.m +++ b/Tests/Application/UI/RKFormTest.m @@ -17,11 +17,13 @@ @interface UISwitch (ControlValue) @implementation UISwitch (ControlValue) -- (NSNumber *)controlValue { +- (NSNumber *)controlValue +{ return [NSNumber numberWithBool:self.isOn]; } -- (void)setControlValue:(NSNumber *)controlValue { +- (void)setControlValue:(NSNumber *)controlValue +{ self.on = [controlValue boolValue]; } @@ -60,7 +62,8 @@ @interface RKFormTest : RKTestCase @implementation RKFormTest -- (void)testCommitValuesBackToTheFormObjectWithBuiltInTypes { +- (void)testCommitValuesBackToTheFormObjectWithBuiltInTypes +{ RKMappableObject *mappableObject = [[RKMappableObject new] autorelease]; RKForm *form = [RKForm formForObject:mappableObject usingBlock:^(RKForm *form) { [form addRowForAttribute:@"stringTest" withControlType:RKFormControlTypeTextField usingBlock:^(RKControlTableItem *tableItem) { @@ -75,7 +78,8 @@ - (void)testCommitValuesBackToTheFormObjectWithBuiltInTypes { assertThatBool([mappableObject.numberTest boolValue], is(equalToBool(YES))); } -- (void)testCommitValuesBackToTheFormObjectFromUserConfiguredControls { +- (void)testCommitValuesBackToTheFormObjectFromUserConfiguredControls +{ RKTestTextField *textField = [[RKTestTextField new] autorelease]; textField.text = @"testing 123"; UISwitch *switchControl = [[UISwitch new] autorelease]; @@ -90,7 +94,8 @@ - (void)testCommitValuesBackToTheFormObjectFromUserConfiguredControls { assertThatBool([mappableObject.numberTest boolValue], is(equalToBool(YES))); } -- (void)testCommitValuesBackToTheFormObjectFromCellKeyPaths { +- (void)testCommitValuesBackToTheFormObjectFromCellKeyPaths +{ RKMappableObject *mappableObject = [[RKMappableObject new] autorelease]; RKForm *form = [RKForm formForObject:mappableObject usingBlock:^(RKForm *form) { [form addRowMappingAttribute:@"stringTest" toKeyPath:@"someTextProperty" onCellWithClass:[RKFormSpecTableViewCell class]]; @@ -111,13 +116,15 @@ - (void)testCommitValuesBackToTheFormObjectFromCellKeyPaths { assertThat(mappableObject.stringTest, is(equalTo(@"testing 123"))); } -- (void)testMakeTheTableItemPassKVCInvocationsThroughToTheUnderlyingMappedControlKeyPath { +- (void)testMakeTheTableItemPassKVCInvocationsThroughToTheUnderlyingMappedControlKeyPath +{ // TODO: Implement me // add a control // invoke valueForKey: with the control value keyPath on the table item... } -- (void)testInvokeValueForKeyPathOnTheControlIfControlValueReturnsNil { +- (void)testInvokeValueForKeyPathOnTheControlIfControlValueReturnsNil +{ // TODO: Implement me // add a custom control to the form // the control value should return nil so that valueForKeyPath is invoked directly diff --git a/Tests/Application/UI/RKTableControllerTest.m b/Tests/Application/UI/RKTableControllerTest.m index 0378a792bb..42383adb9b 100644 --- a/Tests/Application/UI/RKTableControllerTest.m +++ b/Tests/Application/UI/RKTableControllerTest.m @@ -16,7 +16,7 @@ // Expose the object loader delegate for testing purposes... @interface RKTableController () -- (void)animationDidStopAddingSwipeView:(NSString*)animationID finished:(NSNumber*)finished context:(void*)context; +- (void)animationDidStopAddingSwipeView:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context; @end @interface RKTableControllerTestTableViewController : UITableViewController @@ -55,49 +55,55 @@ - (void)tearDown [RKTestFactory tearDown]; } -- (void)testInitializeWithATableViewController { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; +- (void)testInitializeWithATableViewController +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; assertThat(viewController.tableView, is(notNilValue())); - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; assertThat(tableController.viewController, is(equalTo(viewController))); assertThat(tableController.tableView, is(equalTo(viewController.tableView))); } -- (void)testInitializeWithATableViewAndViewController { - UITableView* tableView = [UITableView new]; - RKTableControllerTestViewController* viewController = [RKTableControllerTestViewController new]; - RKTableController* tableController = [RKTableController tableControllerWithTableView:tableView forViewController:viewController]; +- (void)testInitializeWithATableViewAndViewController +{ + UITableView *tableView = [UITableView new]; + RKTableControllerTestViewController *viewController = [RKTableControllerTestViewController new]; + RKTableController *tableController = [RKTableController tableControllerWithTableView:tableView forViewController:viewController]; assertThat(tableController.viewController, is(equalTo(viewController))); assertThat(tableController.tableView, is(equalTo(tableView))); } -- (void)testInitializesToUnloadedState { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testInitializesToUnloadedState +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; assertThatBool([tableController isLoaded], is(equalToBool(NO))); } -- (void)testAlwaysHaveAtLeastOneSection { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; +- (void)testAlwaysHaveAtLeastOneSection +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; assertThat(viewController.tableView, is(notNilValue())); - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; assertThatInt(tableController.sectionCount, is(equalToInt(1))); } -- (void)testDisconnectFromTheTableViewOnDealloc { - NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; +- (void)testDisconnectFromTheTableViewOnDealloc +{ + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; assertThatInt(tableController.sectionCount, is(equalToInt(1))); [pool drain]; assertThat(viewController.tableView.delegate, is(nilValue())); assertThat(viewController.tableView.dataSource, is(nilValue())); } -- (void)testNotDisconnectFromTheTableViewIfDelegateOrDataSourceAreNotSelf { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [[RKTableController alloc] initWithTableView:viewController.tableView viewController:viewController]; +- (void)testNotDisconnectFromTheTableViewIfDelegateOrDataSourceAreNotSelf +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [[RKTableController alloc] initWithTableView:viewController.tableView viewController:viewController]; viewController.tableView.delegate = viewController; viewController.tableView.dataSource = viewController; assertThatInt(tableController.sectionCount, is(equalToInt(1))); @@ -108,71 +114,79 @@ - (void)testNotDisconnectFromTheTableViewIfDelegateOrDataSourceAreNotSelf { #pragma mark - Section Management -- (void)testAddASection { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; - RKTableSection* section = [RKTableSection section]; +- (void)testAddASection +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; + RKTableSection *section = [RKTableSection section]; [tableController addSection:section]; assertThatInt([tableController.sections count], is(equalToInt(2))); } -- (void)testConnectTheSectionToTheTableModelOnAdd { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; - RKTableSection* section = [RKTableSection section]; +- (void)testConnectTheSectionToTheTableModelOnAdd +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; + RKTableSection *section = [RKTableSection section]; [tableController addSection:section]; assertThat(section.tableController, is(equalTo(tableController))); } -- (void)testConnectTheSectionToTheCellMappingsOfTheTableModelWhenNil { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; - RKTableSection* section = [RKTableSection section]; +- (void)testConnectTheSectionToTheCellMappingsOfTheTableModelWhenNil +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; + RKTableSection *section = [RKTableSection section]; assertThat(section.cellMappings, is(nilValue())); [tableController addSection:section]; assertThat(section.cellMappings, is(equalTo(tableController.cellMappings))); } -- (void)testNotConnectTheSectionToTheCellMappingsOfTheTableModelWhenNonNil { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; - RKTableSection* section = [RKTableSection section]; +- (void)testNotConnectTheSectionToTheCellMappingsOfTheTableModelWhenNonNil +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; + RKTableSection *section = [RKTableSection section]; section.cellMappings = [NSMutableDictionary dictionary]; [tableController addSection:section]; assertThatBool(section.cellMappings == tableController.cellMappings, is(equalToBool(NO))); } -- (void)testCountTheSections { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; - RKTableSection* section = [RKTableSection section]; +- (void)testCountTheSections +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; + RKTableSection *section = [RKTableSection section]; [tableController addSection:section]; assertThatInt(tableController.sectionCount, is(equalToInt(2))); } -- (void)testRemoveASection { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; - RKTableSection* section = [RKTableSection section]; +- (void)testRemoveASection +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; + RKTableSection *section = [RKTableSection section]; [tableController addSection:section]; assertThatInt(tableController.sectionCount, is(equalToInt(2))); [tableController removeSection:section]; assertThatInt(tableController.sectionCount, is(equalToInt(1))); } -- (void)testNotLetRemoveTheLastSection { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; - RKTableSection* section = [RKTableSection section]; +- (void)testNotLetRemoveTheLastSection +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; + RKTableSection *section = [RKTableSection section]; [tableController addSection:section]; assertThatInt(tableController.sectionCount, is(equalToInt(2))); [tableController removeSection:section]; } -- (void)testInsertASectionAtATestificIndex { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; - RKTableSection* referenceSection = [RKTableSection section]; +- (void)testInsertASectionAtATestificIndex +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; + RKTableSection *referenceSection = [RKTableSection section]; [tableController addSection:[RKTableSection section]]; [tableController addSection:[RKTableSection section]]; [tableController addSection:[RKTableSection section]]; @@ -182,20 +196,22 @@ - (void)testInsertASectionAtATestificIndex { assertThat([tableController.sections objectAtIndex:2], is(equalTo(referenceSection))); } -- (void)testRemoveASectionByIndex { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; - RKTableSection* section = [RKTableSection section]; +- (void)testRemoveASectionByIndex +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; + RKTableSection *section = [RKTableSection section]; [tableController addSection:section]; assertThatInt(tableController.sectionCount, is(equalToInt(2))); [tableController removeSectionAtIndex:1]; assertThatInt(tableController.sectionCount, is(equalToInt(1))); } -- (void)testRaiseAnExceptionWhenAttemptingToRemoveTheLastSection { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; - NSException* exception = nil; +- (void)testRaiseAnExceptionWhenAttemptingToRemoveTheLastSection +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; + NSException *exception = nil; @try { [tableController removeSectionAtIndex:0]; } @@ -207,10 +223,11 @@ - (void)testRaiseAnExceptionWhenAttemptingToRemoveTheLastSection { } } -- (void)testReturnTheSectionAtAGivenIndex { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; - RKTableSection* referenceSection = [RKTableSection section]; +- (void)testReturnTheSectionAtAGivenIndex +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; + RKTableSection *referenceSection = [RKTableSection section]; [tableController addSection:[RKTableSection section]]; [tableController addSection:[RKTableSection section]]; [tableController addSection:[RKTableSection section]]; @@ -220,9 +237,10 @@ - (void)testReturnTheSectionAtAGivenIndex { assertThat([tableController sectionAtIndex:2], is(equalTo(referenceSection))); } -- (void)testRemoveAllSections { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testRemoveAllSections +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; [tableController addSection:[RKTableSection section]]; [tableController addSection:[RKTableSection section]]; [tableController addSection:[RKTableSection section]]; @@ -232,19 +250,21 @@ - (void)testRemoveAllSections { assertThatInt(tableController.sectionCount, is(equalToInt(1))); } -- (void)testReturnASectionByHeaderTitle { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testReturnASectionByHeaderTitle +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; [tableController addSection:[RKTableSection section]]; [tableController addSection:[RKTableSection section]]; - RKTableSection* titledSection = [RKTableSection section]; + RKTableSection *titledSection = [RKTableSection section]; titledSection.headerTitle = @"Testing"; [tableController addSection:titledSection]; [tableController addSection:[RKTableSection section]]; assertThat([tableController sectionWithHeaderTitle:@"Testing"], is(equalTo(titledSection))); } -- (void)testNotifyTheTableViewOnSectionInsertion { +- (void)testNotifyTheTableViewOnSectionInsertion +{ RKTableControllerTestViewController *viewController = [RKTableControllerTestViewController new]; id mockTableView = [OCMockObject niceMockForClass:[UITableView class]]; RKTableController *tableController = [RKTableController tableControllerWithTableView:mockTableView forViewController:viewController]; @@ -253,7 +273,8 @@ - (void)testNotifyTheTableViewOnSectionInsertion { [mockTableView verify]; } -- (void)testNotifyTheTableViewOnSectionRemoval { +- (void)testNotifyTheTableViewOnSectionRemoval +{ RKTableControllerTestViewController *viewController = [RKTableControllerTestViewController new]; id mockTableView = [OCMockObject niceMockForClass:[UITableView class]]; RKTableController *tableController = [RKTableController tableControllerWithTableView:mockTableView forViewController:viewController]; @@ -265,7 +286,8 @@ - (void)testNotifyTheTableViewOnSectionRemoval { [mockTableView verify]; } -- (void)testNotifyTheTableOfSectionRemovalAndReaddWhenRemovingAllSections { +- (void)testNotifyTheTableOfSectionRemovalAndReaddWhenRemovingAllSections +{ RKTableControllerTestViewController *viewController = [RKTableControllerTestViewController new]; id mockTableView = [OCMockObject niceMockForClass:[UITableView class]]; RKTableController *tableController = [RKTableController tableControllerWithTableView:mockTableView forViewController:viewController]; @@ -280,14 +302,15 @@ - (void)testNotifyTheTableOfSectionRemovalAndReaddWhenRemovingAllSections { #pragma mark - UITableViewDataSource Tests -- (void)testRaiseAnExceptionIfSentAMessageWithATableViewItIsNotBoundTo { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; - NSException* exception = nil; +- (void)testRaiseAnExceptionIfSentAMessageWithATableViewItIsNotBoundTo +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; + NSException *exception = nil; @try { [tableController numberOfSectionsInTableView:[UITableView new]]; } - @catch (NSException* e) { + @catch (NSException *e) { exception = e; } @finally { @@ -295,47 +318,52 @@ - (void)testRaiseAnExceptionIfSentAMessageWithATableViewItIsNotBoundTo { } } -- (void)testReturnTheNumberOfSectionsInTableView { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testReturnTheNumberOfSectionsInTableView +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; assertThatInt([tableController numberOfSectionsInTableView:viewController.tableView], is(equalToInt(1))); [tableController addSection:[RKTableSection section]]; assertThatInt([tableController numberOfSectionsInTableView:viewController.tableView], is(equalToInt(2))); } -- (void)testReturnTheNumberOfRowsInSectionInTableView { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testReturnTheNumberOfRowsInSectionInTableView +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; assertThatInt([tableController tableView:viewController.tableView numberOfRowsInSection:0], is(equalToInt(0))); - NSArray* objects = [NSArray arrayWithObject:@"one"]; + NSArray *objects = [NSArray arrayWithObject:@"one"]; [tableController loadObjects:objects]; assertThatInt([tableController tableView:viewController.tableView numberOfRowsInSection:0], is(equalToInt(1))); } -- (void)testReturnTheHeaderTitleForSection { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; - RKTableSection* section = [RKTableSection section]; +- (void)testReturnTheHeaderTitleForSection +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; + RKTableSection *section = [RKTableSection section]; [tableController addSection:section]; assertThat([tableController tableView:viewController.tableView titleForHeaderInSection:1], is(nilValue())); section.headerTitle = @"RestKit!"; assertThat([tableController tableView:viewController.tableView titleForHeaderInSection:1], is(equalTo(@"RestKit!"))); } -- (void)testReturnTheTitleForFooterInSection { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; - RKTableSection* section = [RKTableSection section]; +- (void)testReturnTheTitleForFooterInSection +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; + RKTableSection *section = [RKTableSection section]; [tableController addSection:section]; assertThat([tableController tableView:viewController.tableView titleForFooterInSection:1], is(nilValue())); section.footerTitle = @"RestKit!"; assertThat([tableController tableView:viewController.tableView titleForFooterInSection:1], is(equalTo(@"RestKit!"))); } -- (void)testReturnTheNumberOfRowsAcrossAllSections { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; - RKTableSection* section = [RKTableSection section]; +- (void)testReturnTheNumberOfRowsAcrossAllSections +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; + RKTableSection *section = [RKTableSection section]; id sectionMock = [OCMockObject partialMockForObject:section]; NSUInteger rowCount = 5; [[[sectionMock stub] andReturnValue:OCMOCK_VALUE(rowCount)] rowCount]; @@ -343,16 +371,17 @@ - (void)testReturnTheNumberOfRowsAcrossAllSections { assertThatInt(tableController.rowCount, is(equalToInt(5))); } -- (void)testReturnTheTableViewCellForRowAtIndexPath { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; - RKTableItem* item = [RKTableItem tableItemWithText:@"Test!" detailText:@"Details!" image:nil]; - [tableController loadTableItems:[NSArray arrayWithObject:item] inSection:0 withMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { +- (void)testReturnTheTableViewCellForRowAtIndexPath +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; + RKTableItem *item = [RKTableItem tableItemWithText:@"Test!" detailText:@"Details!" image:nil]; + [tableController loadTableItems:[NSArray arrayWithObject:item] inSection:0 withMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { // Detail text label won't appear with default style... cellMapping.style = UITableViewCellStyleValue1; [cellMapping addDefaultMappings]; }]]; - UITableViewCell* cell = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; + UITableViewCell *cell = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; assertThat(cell.textLabel.text, is(equalTo(@"Test!"))); assertThat(cell.detailTextLabel.text, is(equalTo(@"Details!"))); @@ -360,32 +389,36 @@ - (void)testReturnTheTableViewCellForRowAtIndexPath { #pragma mark - Table Cell Mapping -- (void)testInitializeCellMappings { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testInitializeCellMappings +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; assertThat(tableController.cellMappings, is(notNilValue())); } -- (void)testRegisterMappingsForObjectsToTableViewCell { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testRegisterMappingsForObjectsToTableViewCell +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; assertThat([tableController.cellMappings cellMappingForClass:[RKTestUser class]], is(nilValue())); [tableController mapObjectsWithClass:[RKTestUser class] toTableCellsWithMapping:[RKTableViewCellMapping cellMapping]]; - RKObjectMapping* mapping = [tableController.cellMappings cellMappingForClass:[RKTestUser class]]; + RKObjectMapping *mapping = [tableController.cellMappings cellMappingForClass:[RKTestUser class]]; assertThat(mapping, isNot(nilValue())); assertThatBool([mapping.objectClass isSubclassOfClass:[UITableViewCell class]], is(equalToBool(YES))); } -- (void)testDefaultTheReuseIdentifierToTheNameOfTheObjectClass { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testDefaultTheReuseIdentifierToTheNameOfTheObjectClass +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; assertThat([tableController.cellMappings cellMappingForClass:[RKTestUser class]], is(nilValue())); - RKTableViewCellMapping* cellMapping = [RKTableViewCellMapping cellMapping]; + RKTableViewCellMapping *cellMapping = [RKTableViewCellMapping cellMapping]; [tableController mapObjectsWithClass:[RKTestUser class] toTableCellsWithMapping:cellMapping]; assertThat(cellMapping.reuseIdentifier, is(equalTo(@"UITableViewCell"))); } -- (void)testDefaultTheReuseIdentifierToTheNameOfTheObjectClassWhenCreatingMappingWithBlockSyntax { +- (void)testDefaultTheReuseIdentifierToTheNameOfTheObjectClassWhenCreatingMappingWithBlockSyntax +{ RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; assertThat([tableController.cellMappings cellMappingForClass:[RKTestUser class]], is(nilValue())); @@ -396,97 +429,105 @@ - (void)testDefaultTheReuseIdentifierToTheNameOfTheObjectClassWhenCreatingMappin assertThat(cellMapping.reuseIdentifier, is(equalTo(@"RKTestUserTableViewCell"))); } -- (void)testReturnTheObjectForARowAtIndexPath { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; - RKTestUser* user = [RKTestUser user]; +- (void)testReturnTheObjectForARowAtIndexPath +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; + RKTestUser *user = [RKTestUser user]; [tableController loadObjects:[NSArray arrayWithObject:user]]; - NSIndexPath* indexPath = [NSIndexPath indexPathForRow:0 inSection:0]; + NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0]; assertThatBool(user == [tableController objectForRowAtIndexPath:indexPath], is(equalToBool(YES))); } -- (void)testReturnTheCellMappingForTheRowAtIndexPath { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; - RKTableViewCellMapping* cellMapping = [RKTableViewCellMapping cellMapping]; +- (void)testReturnTheCellMappingForTheRowAtIndexPath +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; + RKTableViewCellMapping *cellMapping = [RKTableViewCellMapping cellMapping]; [tableController mapObjectsWithClass:[RKTestUser class] toTableCellsWithMapping:cellMapping]; [tableController loadObjects:[NSArray arrayWithObject:[RKTestUser user]]]; - NSIndexPath* indexPath = [NSIndexPath indexPathForRow:0 inSection:0]; + NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0]; assertThat([tableController cellMappingForObjectAtIndexPath:indexPath], is(equalTo(cellMapping))); } -- (void)testReturnATableViewCellForTheObjectAtAGivenIndexPath { - RKMappableObject* object = [RKMappableObject new]; +- (void)testReturnATableViewCellForTheObjectAtAGivenIndexPath +{ + RKMappableObject *object = [RKMappableObject new]; object.stringTest = @"Testing!!"; - RKTableViewCellMapping* cellMapping = [RKTableViewCellMapping mappingForClass:[UITableViewCell class]]; + RKTableViewCellMapping *cellMapping = [RKTableViewCellMapping mappingForClass:[UITableViewCell class]]; [cellMapping mapKeyPath:@"stringTest" toAttribute:@"textLabel.text"]; - NSArray* objects = [NSArray arrayWithObject:object]; - RKTableViewCellMappings* mappings = [RKTableViewCellMappings new]; + NSArray *objects = [NSArray arrayWithObject:object]; + RKTableViewCellMappings *mappings = [RKTableViewCellMappings new]; [mappings setCellMapping:cellMapping forClass:[RKMappableObject class]]; - RKTableSection* section = [RKTableSection sectionForObjects:objects withMappings:mappings]; - UITableViewController* tableViewController = [UITableViewController new]; - tableViewController.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,0,0,0) style:UITableViewStylePlain]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:tableViewController]; + RKTableSection *section = [RKTableSection sectionForObjects:objects withMappings:mappings]; + UITableViewController *tableViewController = [UITableViewController new]; + tableViewController.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStylePlain]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:tableViewController]; [tableController insertSection:section atIndex:0]; tableController.cellMappings = mappings; - UITableViewCell* cell = [tableController cellForObjectAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; + UITableViewCell *cell = [tableController cellForObjectAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; assertThat(cell, isNot(nilValue())); assertThat(cell.textLabel.text, is(equalTo(@"Testing!!"))); } -- (void)testChangeTheReuseIdentifierWhenMutatedWithinTheBlockInitializer { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testChangeTheReuseIdentifierWhenMutatedWithinTheBlockInitializer +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; assertThat([tableController.cellMappings cellMappingForClass:[RKTestUser class]], is(nilValue())); [tableController mapObjectsWithClass:[RKTestUser class] toTableCellsWithMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { cellMapping.cellClass = [RKTestUserTableViewCell class]; cellMapping.reuseIdentifier = @"RKTestUserOverride"; }]]; - RKTableViewCellMapping* userCellMapping = [tableController.cellMappings cellMappingForClass:[RKTestUser class]]; + RKTableViewCellMapping *userCellMapping = [tableController.cellMappings cellMappingForClass:[RKTestUser class]]; assertThat(userCellMapping, isNot(nilValue())); assertThat(userCellMapping.reuseIdentifier, is(equalTo(@"RKTestUserOverride"))); } #pragma mark - Static Object Loading -- (void)testLoadAnArrayOfObjects { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; - NSArray* objects = [NSArray arrayWithObject:@"one"]; +- (void)testLoadAnArrayOfObjects +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; + NSArray *objects = [NSArray arrayWithObject:@"one"]; assertThat([tableController sectionAtIndex:0].objects, is(empty())); [tableController loadObjects:objects]; assertThat([tableController sectionAtIndex:0].objects, is(equalTo(objects))); } -- (void)testLoadAnArrayOfObjectsToTheTestifiedSection { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testLoadAnArrayOfObjectsToTheTestifiedSection +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; [tableController addSection:[RKTableSection section]]; - NSArray* objects = [NSArray arrayWithObject:@"one"]; + NSArray *objects = [NSArray arrayWithObject:@"one"]; assertThat([tableController sectionAtIndex:1].objects, is(empty())); [tableController loadObjects:objects inSection:1]; assertThat([tableController sectionAtIndex:1].objects, is(equalTo(objects))); } -- (void)testLoadAnArrayOfTableItems { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; - NSArray* tableItems = [RKTableItem tableItemsFromStrings:@"One", @"Two", @"Three", nil]; +- (void)testLoadAnArrayOfTableItems +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; + NSArray *tableItems = [RKTableItem tableItemsFromStrings:@"One", @"Two", @"Three", nil]; [tableController loadTableItems:tableItems]; assertThatBool([tableController isLoaded], is(equalToBool(YES))); assertThatInt(tableController.rowCount, is(equalToInt(3))); - UITableViewCell* cellOne = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; - UITableViewCell* cellTwo = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]]; - UITableViewCell* cellThree = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]]; + UITableViewCell *cellOne = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; + UITableViewCell *cellTwo = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]]; + UITableViewCell *cellThree = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]]; assertThat(cellOne.textLabel.text, is(equalTo(@"One"))); assertThat(cellTwo.textLabel.text, is(equalTo(@"Two"))); assertThat(cellThree.textLabel.text, is(equalTo(@"Three"))); } -- (void)testAllowYouToTriggerAnEmptyLoad { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testAllowYouToTriggerAnEmptyLoad +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; assertThatBool([tableController isLoaded], is(equalToBool(NO))); [tableController loadEmpty]; assertThatBool([tableController isLoaded], is(equalToBool(YES))); @@ -495,22 +536,23 @@ - (void)testAllowYouToTriggerAnEmptyLoad { #pragma mark - Network Load -- (void)testLoadCollectionOfObjectsAndMapThemIntoTableViewCells { - RKObjectManager* objectManager = [RKTestFactory objectManager]; +- (void)testLoadCollectionOfObjectsAndMapThemIntoTableViewCells +{ + RKObjectManager *objectManager = [RKTestFactory objectManager]; objectManager.client.cachePolicy = RKRequestCachePolicyNone; - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; tableController.objectManager = objectManager; - [tableController mapObjectsWithClass:[RKTestUser class] toTableCellsWithMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* mapping) { + [tableController mapObjectsWithClass:[RKTestUser class] toTableCellsWithMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *mapping) { mapping.cellClass = [RKTestUserTableViewCell class]; [mapping mapKeyPath:@"name" toAttribute:@"textLabel.text"]; [mapping mapKeyPath:@"nickName" toAttribute:@"detailTextLabel.text"]; }]]; - RKTableControllerTestDelegate* delegate = [RKTableControllerTestDelegate tableControllerDelegate]; + RKTableControllerTestDelegate *delegate = [RKTableControllerTestDelegate tableControllerDelegate]; delegate.timeout = 10; tableController.delegate = delegate; - [tableController loadTableFromResourcePath:@"/JSON/users.json" usingBlock:^(RKObjectLoader* objectLoader) { - objectLoader.objectMapping = [RKObjectMapping mappingForClass:[RKTestUser class] usingBlock:^(RKObjectMapping* mapping) { + [tableController loadTableFromResourcePath:@"/JSON/users.json" usingBlock:^(RKObjectLoader *objectLoader) { + objectLoader.objectMapping = [RKObjectMapping mappingForClass:[RKTestUser class] usingBlock:^(RKObjectMapping *mapping) { [mapping mapAttributes:@"name", nil]; }]; }]; @@ -519,22 +561,24 @@ - (void)testLoadCollectionOfObjectsAndMapThemIntoTableViewCells { assertThatInt(tableController.rowCount, is(equalToInt(3))); } -- (void)testSetTheModelToTheLoadedStateIfObjectsAreLoadedSuccessfully { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testSetTheModelToTheLoadedStateIfObjectsAreLoadedSuccessfully +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; assertThatBool([tableController isLoaded], is(equalToBool(NO))); - NSArray* objects = [NSArray arrayWithObject:[RKTestUser new]]; + NSArray *objects = [NSArray arrayWithObject:[RKTestUser new]]; id mockLoader = [OCMockObject mockForClass:[RKObjectLoader class]]; [tableController objectLoader:mockLoader didLoadObjects:objects]; assertThatBool([tableController isLoading], is(equalToBool(NO))); assertThatBool([tableController isLoaded], is(equalToBool(YES))); } -- (void)testSetTheModelToErrorStateIfTheObjectLoaderFailsWithAnError { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testSetTheModelToErrorStateIfTheObjectLoaderFailsWithAnError +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; id mockObjectLoader = [OCMockObject niceMockForClass:[RKObjectLoader class]]; - NSError* error = [NSError errorWithDomain:@"Test" code:0 userInfo:nil]; + NSError *error = [NSError errorWithDomain:@"Test" code:0 userInfo:nil]; [tableController objectLoader:mockObjectLoader didFailWithError:error]; assertThatBool([tableController isLoading], is(equalToBool(NO))); assertThatBool([tableController isLoaded], is(equalToBool(YES))); @@ -542,32 +586,34 @@ - (void)testSetTheModelToErrorStateIfTheObjectLoaderFailsWithAnError { assertThatBool([tableController isEmpty], is(equalToBool(YES))); } -- (void)testErrorIsClearedAfterSubsequentLoad { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testErrorIsClearedAfterSubsequentLoad +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; id mockObjectLoader = [OCMockObject niceMockForClass:[RKObjectLoader class]]; - NSError* error = [NSError errorWithDomain:@"Test" code:0 userInfo:nil]; + NSError *error = [NSError errorWithDomain:@"Test" code:0 userInfo:nil]; [tableController objectLoader:mockObjectLoader didFailWithError:error]; assertThatBool([tableController isLoading], is(equalToBool(NO))); assertThatBool([tableController isLoaded], is(equalToBool(YES))); assertThatBool([tableController isError], is(equalToBool(YES))); assertThatBool([tableController isEmpty], is(equalToBool(YES))); - + [tableController objectLoader:mockObjectLoader didLoadObjects:[NSArray array]]; assertThatBool([tableController isError], is(equalToBool(NO))); assertThat(tableController.error, is(nilValue())); } -- (void)testDisplayOfErrorImageTakesPresendenceOverEmpty { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testDisplayOfErrorImageTakesPresendenceOverEmpty +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; UIImage *imageForEmpty = [RKTestFixture imageWithContentsOfFixture:@"blake.png"]; UIImage *imageForError = [imageForEmpty copy]; tableController.imageForEmpty = imageForEmpty; - tableController.imageForError = imageForError; - + tableController.imageForError = imageForError; + id mockObjectLoader = [OCMockObject niceMockForClass:[RKObjectLoader class]]; - NSError* error = [NSError errorWithDomain:@"Test" code:0 userInfo:nil]; + NSError *error = [NSError errorWithDomain:@"Test" code:0 userInfo:nil]; [tableController objectLoader:mockObjectLoader didFailWithError:error]; assertThatBool([tableController isLoading], is(equalToBool(NO))); assertThatBool([tableController isLoaded], is(equalToBool(YES))); @@ -579,50 +625,53 @@ - (void)testDisplayOfErrorImageTakesPresendenceOverEmpty { assertThat(overlayImage, is(equalTo(imageForError))); } -- (void)testBitwiseLoadingTransition { +- (void)testBitwiseLoadingTransition +{ RKTableControllerState oldState = RKTableControllerStateNotYetLoaded; RKTableControllerState newState = RKTableControllerStateLoading; - + BOOL loadingTransitioned = ((oldState ^ newState) & RKTableControllerStateLoading); assertThatBool(loadingTransitioned, is(equalToBool(YES))); - + oldState = RKTableControllerStateOffline | RKTableControllerStateEmpty; newState = RKTableControllerStateOffline | RKTableControllerStateEmpty | RKTableControllerStateLoading; loadingTransitioned = ((oldState ^ newState) & RKTableControllerStateLoading); assertThatBool(loadingTransitioned, is(equalToBool(YES))); - + oldState = RKTableControllerStateNormal; newState = RKTableControllerStateLoading; loadingTransitioned = ((oldState ^ newState) & RKTableControllerStateLoading); assertThatBool(loadingTransitioned, is(equalToBool(YES))); - + oldState = RKTableControllerStateOffline | RKTableControllerStateEmpty | RKTableControllerStateLoading; newState = RKTableControllerStateOffline | RKTableControllerStateLoading; loadingTransitioned = ((oldState ^ newState) & RKTableControllerStateLoading); assertThatBool(loadingTransitioned, is(equalToBool(NO))); - + oldState = RKTableControllerStateNotYetLoaded; newState = RKTableControllerStateOffline; loadingTransitioned = ((oldState ^ newState) & RKTableControllerStateLoading); assertThatBool(loadingTransitioned, is(equalToBool(NO))); } -- (void)testSetTheModelToAnEmptyStateIfTheObjectLoaderReturnsAnEmptyCollection { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testSetTheModelToAnEmptyStateIfTheObjectLoaderReturnsAnEmptyCollection +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; assertThatBool([tableController isLoaded], is(equalToBool(NO))); - NSArray* objects = [NSArray array]; + NSArray *objects = [NSArray array]; id mockLoader = [OCMockObject mockForClass:[RKObjectLoader class]]; [tableController objectLoader:mockLoader didLoadObjects:objects]; assertThatBool([tableController isLoading], is(equalToBool(NO))); assertThatBool([tableController isEmpty], is(equalToBool(YES))); } -- (void)testSetTheModelToALoadedStateEvenIfTheObjectLoaderReturnsAnEmptyCollection { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testSetTheModelToALoadedStateEvenIfTheObjectLoaderReturnsAnEmptyCollection +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; assertThatBool([tableController isLoaded], is(equalToBool(NO))); - NSArray* objects = [NSArray array]; + NSArray *objects = [NSArray array]; id mockLoader = [OCMockObject mockForClass:[RKObjectLoader class]]; [tableController objectLoader:mockLoader didLoadObjects:objects]; assertThatBool([tableController isLoading], is(equalToBool(NO))); @@ -630,9 +679,10 @@ - (void)testSetTheModelToALoadedStateEvenIfTheObjectLoaderReturnsAnEmptyCollecti assertThatBool([tableController isLoaded], is(equalToBool(YES))); } -- (void)testEnterTheLoadingStateWhenTheRequestStartsLoading { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testEnterTheLoadingStateWhenTheRequestStartsLoading +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; assertThatBool([tableController isLoaded], is(equalToBool(NO))); assertThatBool([tableController isLoading], is(equalToBool(NO))); id mockLoader = [OCMockObject mockForClass:[RKObjectLoader class]]; @@ -640,9 +690,10 @@ - (void)testEnterTheLoadingStateWhenTheRequestStartsLoading { assertThatBool([tableController isLoading], is(equalToBool(YES))); } -- (void)testExitTheLoadingStateWhenTheRequestFinishesLoading { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testExitTheLoadingStateWhenTheRequestFinishesLoading +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; assertThatBool([tableController isLoaded], is(equalToBool(NO))); assertThatBool([tableController isLoading], is(equalToBool(NO))); id mockLoader = [OCMockObject niceMockForClass:[RKObjectLoader class]]; @@ -652,9 +703,10 @@ - (void)testExitTheLoadingStateWhenTheRequestFinishesLoading { assertThatBool([tableController isLoading], is(equalToBool(NO))); } -- (void)testClearTheLoadingStateWhenARequestIsCancelled { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testClearTheLoadingStateWhenARequestIsCancelled +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; assertThatBool([tableController isLoaded], is(equalToBool(NO))); assertThatBool([tableController isLoading], is(equalToBool(NO))); id mockLoader = [OCMockObject mockForClass:[RKObjectLoader class]]; @@ -664,9 +716,10 @@ - (void)testClearTheLoadingStateWhenARequestIsCancelled { assertThatBool([tableController isLoading], is(equalToBool(NO))); } -- (void)testClearTheLoadingStateWhenARequestTimesOut { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testClearTheLoadingStateWhenARequestTimesOut +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; assertThatBool([tableController isLoaded], is(equalToBool(NO))); assertThatBool([tableController isLoading], is(equalToBool(NO))); id mockLoader = [OCMockObject mockForClass:[RKObjectLoader class]]; @@ -676,27 +729,29 @@ - (void)testClearTheLoadingStateWhenARequestTimesOut { assertThatBool([tableController isLoading], is(equalToBool(NO))); } -- (void)testDoSomethingWhenTheRequestLoadsAnUnexpectedResponse { +- (void)testDoSomethingWhenTheRequestLoadsAnUnexpectedResponse +{ RKLogCritical(@"PENDING - Undefined Behavior!!!"); } -- (void)testLoadCollectionOfObjectsAndMapThemIntoSections { - RKObjectManager* objectManager = [RKTestFactory objectManager]; +- (void)testLoadCollectionOfObjectsAndMapThemIntoSections +{ + RKObjectManager *objectManager = [RKTestFactory objectManager]; objectManager.client.cachePolicy = RKRequestCachePolicyNone; - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; tableController.objectManager = objectManager; - [tableController mapObjectsWithClass:[RKTestUser class] toTableCellsWithMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* mapping) { + [tableController mapObjectsWithClass:[RKTestUser class] toTableCellsWithMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *mapping) { mapping.cellClass = [RKTestUserTableViewCell class]; [mapping mapKeyPath:@"name" toAttribute:@"textLabel.text"]; [mapping mapKeyPath:@"nickName" toAttribute:@"detailTextLabel.text"]; }]]; tableController.sectionNameKeyPath = @"name"; - RKTableControllerTestDelegate* delegate = [RKTableControllerTestDelegate tableControllerDelegate]; + RKTableControllerTestDelegate *delegate = [RKTableControllerTestDelegate tableControllerDelegate]; delegate.timeout = 10; tableController.delegate = delegate; - [tableController loadTableFromResourcePath:@"/JSON/users.json" usingBlock:^(RKObjectLoader* objectLoader) { - objectLoader.objectMapping = [RKObjectMapping mappingForClass:[RKTestUser class] usingBlock:^(RKObjectMapping* mapping) { + [tableController loadTableFromResourcePath:@"/JSON/users.json" usingBlock:^(RKObjectLoader *objectLoader) { + objectLoader.objectMapping = [RKObjectMapping mappingForClass:[RKTestUser class] usingBlock:^(RKObjectMapping *mapping) { [mapping mapAttributes:@"name", nil]; }]; }]; @@ -706,23 +761,24 @@ - (void)testLoadCollectionOfObjectsAndMapThemIntoSections { assertThatInt(tableController.rowCount, is(equalToInt(3))); } -- (void)testLoadingACollectionOfObjectsIntoSectionsAndThenLoadingAnEmptyCollectionChangesTableToEmpty { - RKObjectManager* objectManager = [RKTestFactory objectManager]; +- (void)testLoadingACollectionOfObjectsIntoSectionsAndThenLoadingAnEmptyCollectionChangesTableToEmpty +{ + RKObjectManager *objectManager = [RKTestFactory objectManager]; objectManager.client.cachePolicy = RKRequestCachePolicyNone; - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; tableController.objectManager = objectManager; - [tableController mapObjectsWithClass:[RKTestUser class] toTableCellsWithMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* mapping) { + [tableController mapObjectsWithClass:[RKTestUser class] toTableCellsWithMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *mapping) { mapping.cellClass = [RKTestUserTableViewCell class]; [mapping mapKeyPath:@"name" toAttribute:@"textLabel.text"]; [mapping mapKeyPath:@"nickName" toAttribute:@"detailTextLabel.text"]; }]]; tableController.sectionNameKeyPath = @"name"; - RKTableControllerTestDelegate* delegate = [RKTableControllerTestDelegate tableControllerDelegate]; + RKTableControllerTestDelegate *delegate = [RKTableControllerTestDelegate tableControllerDelegate]; delegate.timeout = 10; tableController.delegate = delegate; - [tableController loadTableFromResourcePath:@"/JSON/users.json" usingBlock:^(RKObjectLoader* objectLoader) { - objectLoader.objectMapping = [RKObjectMapping mappingForClass:[RKTestUser class] usingBlock:^(RKObjectMapping* mapping) { + [tableController loadTableFromResourcePath:@"/JSON/users.json" usingBlock:^(RKObjectLoader *objectLoader) { + objectLoader.objectMapping = [RKObjectMapping mappingForClass:[RKTestUser class] usingBlock:^(RKObjectMapping *mapping) { [mapping mapAttributes:@"name", nil]; }]; }]; @@ -733,8 +789,8 @@ - (void)testLoadingACollectionOfObjectsIntoSectionsAndThenLoadingAnEmptyCollecti delegate = [RKTableControllerTestDelegate tableControllerDelegate]; delegate.timeout = 10; tableController.delegate = delegate; - [tableController loadTableFromResourcePath:@"/204" usingBlock:^(RKObjectLoader* objectLoader) { - objectLoader.objectMapping = [RKObjectMapping mappingForClass:[RKTestUser class] usingBlock:^(RKObjectMapping* mapping) { + [tableController loadTableFromResourcePath:@"/204" usingBlock:^(RKObjectLoader *objectLoader) { + objectLoader.objectMapping = [RKObjectMapping mappingForClass:[RKTestUser class] usingBlock:^(RKObjectMapping *mapping) { [mapping mapAttributes:@"name", nil]; }]; }]; @@ -745,12 +801,13 @@ - (void)testLoadingACollectionOfObjectsIntoSectionsAndThenLoadingAnEmptyCollecti #pragma mark - RKTableViewDelegate Tests -- (void)testNotifyTheDelegateWhenLoadingStarts { - RKObjectManager* objectManager = [RKTestFactory objectManager]; - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testNotifyTheDelegateWhenLoadingStarts +{ + RKObjectManager *objectManager = [RKTestFactory objectManager]; + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; tableController.objectManager = objectManager; - [tableController mapObjectsWithClass:[RKTestUser class] toTableCellsWithMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* mapping) { + [tableController mapObjectsWithClass:[RKTestUser class] toTableCellsWithMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *mapping) { mapping.cellClass = [RKTestUserTableViewCell class]; [mapping mapKeyPath:@"name" toAttribute:@"textLabel.text"]; [mapping mapKeyPath:@"nickName" toAttribute:@"detailTextLabel.text"]; @@ -758,8 +815,8 @@ - (void)testNotifyTheDelegateWhenLoadingStarts { id mockDelegate = [OCMockObject partialMockForObject:[RKTableControllerTestDelegate new]]; [[[mockDelegate expect] andForwardToRealObject] tableControllerDidStartLoad:tableController]; tableController.delegate = mockDelegate; - [tableController loadTableFromResourcePath:@"/JSON/users.json" usingBlock:^(RKObjectLoader* objectLoader) { - objectLoader.objectMapping = [RKObjectMapping mappingForClass:[RKTestUser class] usingBlock:^(RKObjectMapping* mapping) { + [tableController loadTableFromResourcePath:@"/JSON/users.json" usingBlock:^(RKObjectLoader *objectLoader) { + objectLoader.objectMapping = [RKObjectMapping mappingForClass:[RKTestUser class] usingBlock:^(RKObjectMapping *mapping) { [mapping mapAttributes:@"name", nil]; }]; }]; @@ -767,22 +824,23 @@ - (void)testNotifyTheDelegateWhenLoadingStarts { STAssertNoThrow([mockDelegate verify], nil); } -- (void)testNotifyTheDelegateWhenLoadingFinishes { - RKObjectManager* objectManager = [RKTestFactory objectManager]; - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testNotifyTheDelegateWhenLoadingFinishes +{ + RKObjectManager *objectManager = [RKTestFactory objectManager]; + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; tableController.objectManager = objectManager; - [tableController mapObjectsWithClass:[RKTestUser class] toTableCellsWithMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* mapping) { + [tableController mapObjectsWithClass:[RKTestUser class] toTableCellsWithMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *mapping) { mapping.cellClass = [RKTestUserTableViewCell class]; [mapping mapKeyPath:@"name" toAttribute:@"textLabel.text"]; [mapping mapKeyPath:@"nickName" toAttribute:@"detailTextLabel.text"]; }]]; - RKTableControllerTestDelegate* delegate = [RKTableControllerTestDelegate new]; + RKTableControllerTestDelegate *delegate = [RKTableControllerTestDelegate new]; id mockDelegate = [OCMockObject partialMockForObject:delegate]; [[[mockDelegate expect] andForwardToRealObject] tableControllerDidFinishLoad:tableController]; tableController.delegate = mockDelegate; - [tableController loadTableFromResourcePath:@"/JSON/users.json" usingBlock:^(RKObjectLoader* objectLoader) { - objectLoader.objectMapping = [RKObjectMapping mappingForClass:[RKTestUser class] usingBlock:^(RKObjectMapping* mapping) { + [tableController loadTableFromResourcePath:@"/JSON/users.json" usingBlock:^(RKObjectLoader *objectLoader) { + objectLoader.objectMapping = [RKObjectMapping mappingForClass:[RKTestUser class] usingBlock:^(RKObjectMapping *mapping) { [mapping mapAttributes:@"name", nil]; }]; }]; @@ -790,22 +848,23 @@ - (void)testNotifyTheDelegateWhenLoadingFinishes { STAssertNoThrow([mockDelegate verify], nil); } -- (void)testNotifyTheDelegateOnDidFinalizeLoad { - RKObjectManager* objectManager = [RKTestFactory objectManager]; - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testNotifyTheDelegateOnDidFinalizeLoad +{ + RKObjectManager *objectManager = [RKTestFactory objectManager]; + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; tableController.objectManager = objectManager; - [tableController mapObjectsWithClass:[RKTestUser class] toTableCellsWithMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* mapping) { + [tableController mapObjectsWithClass:[RKTestUser class] toTableCellsWithMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *mapping) { mapping.cellClass = [RKTestUserTableViewCell class]; [mapping mapKeyPath:@"name" toAttribute:@"textLabel.text"]; [mapping mapKeyPath:@"nickName" toAttribute:@"detailTextLabel.text"]; }]]; - RKTableControllerTestDelegate* delegate = [RKTableControllerTestDelegate new]; + RKTableControllerTestDelegate *delegate = [RKTableControllerTestDelegate new]; id mockDelegate = [OCMockObject partialMockForObject:delegate]; [[mockDelegate expect] tableControllerDidFinalizeLoad:tableController]; tableController.delegate = mockDelegate; - [tableController loadTableFromResourcePath:@"/JSON/users.json" usingBlock:^(RKObjectLoader* objectLoader) { - objectLoader.objectMapping = [RKObjectMapping mappingForClass:[RKTestUser class] usingBlock:^(RKObjectMapping* mapping) { + [tableController loadTableFromResourcePath:@"/JSON/users.json" usingBlock:^(RKObjectLoader *objectLoader) { + objectLoader.objectMapping = [RKObjectMapping mappingForClass:[RKTestUser class] usingBlock:^(RKObjectMapping *mapping) { [mapping mapAttributes:@"name", nil]; }]; }]; @@ -813,22 +872,23 @@ - (void)testNotifyTheDelegateOnDidFinalizeLoad { STAssertNoThrow([mockDelegate verify], nil); } -- (void)testNotifyTheDelegateWhenAnErrorOccurs { - RKObjectManager* objectManager = [RKTestFactory objectManager]; - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testNotifyTheDelegateWhenAnErrorOccurs +{ + RKObjectManager *objectManager = [RKTestFactory objectManager]; + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; tableController.objectManager = objectManager; - [tableController mapObjectsWithClass:[RKTestUser class] toTableCellsWithMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* mapping) { + [tableController mapObjectsWithClass:[RKTestUser class] toTableCellsWithMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *mapping) { mapping.cellClass = [RKTestUserTableViewCell class]; [mapping mapKeyPath:@"name" toAttribute:@"textLabel.text"]; [mapping mapKeyPath:@"nickName" toAttribute:@"detailTextLabel.text"]; }]]; - RKTableControllerTestDelegate* delegate = [RKTableControllerTestDelegate new]; + RKTableControllerTestDelegate *delegate = [RKTableControllerTestDelegate new]; id mockDelegate = [OCMockObject partialMockForObject:delegate]; [[[mockDelegate expect] andForwardToRealObject] tableController:tableController didFailLoadWithError:OCMOCK_ANY]; tableController.delegate = mockDelegate; - [tableController loadTableFromResourcePath:@"/fail" usingBlock:^(RKObjectLoader* objectLoader) { - objectLoader.objectMapping = [RKObjectMapping mappingForClass:[RKTestUser class] usingBlock:^(RKObjectMapping* mapping) { + [tableController loadTableFromResourcePath:@"/fail" usingBlock:^(RKObjectLoader *objectLoader) { + objectLoader.objectMapping = [RKObjectMapping mappingForClass:[RKTestUser class] usingBlock:^(RKObjectMapping *mapping) { [mapping mapAttributes:@"name", nil]; }]; }]; @@ -836,24 +896,25 @@ - (void)testNotifyTheDelegateWhenAnErrorOccurs { STAssertNoThrow([mockDelegate verify], nil); } -- (void)testNotifyTheDelegateWhenAnEmptyCollectionIsLoaded { - RKObjectManager* objectManager = [RKTestFactory objectManager]; +- (void)testNotifyTheDelegateWhenAnEmptyCollectionIsLoaded +{ + RKObjectManager *objectManager = [RKTestFactory objectManager]; objectManager.client.cachePolicy = RKRequestCachePolicyNone; - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; tableController.objectManager = objectManager; - [tableController mapObjectsWithClass:[RKTestUser class] toTableCellsWithMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* mapping) { + [tableController mapObjectsWithClass:[RKTestUser class] toTableCellsWithMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *mapping) { mapping.cellClass = [RKTestUserTableViewCell class]; [mapping mapKeyPath:@"name" toAttribute:@"textLabel.text"]; [mapping mapKeyPath:@"nickName" toAttribute:@"detailTextLabel.text"]; }]]; - RKTableControllerTestDelegate* delegate = [RKTableControllerTestDelegate new]; + RKTableControllerTestDelegate *delegate = [RKTableControllerTestDelegate new]; delegate.timeout = 5; id mockDelegate = [OCMockObject partialMockForObject:delegate]; [[[mockDelegate expect] andForwardToRealObject] tableControllerDidBecomeEmpty:tableController]; tableController.delegate = mockDelegate; - [tableController loadTableFromResourcePath:@"/empty/array" usingBlock:^(RKObjectLoader* objectLoader) { - objectLoader.objectMapping = [RKObjectMapping mappingForClass:[RKTestUser class] usingBlock:^(RKObjectMapping* mapping) { + [tableController loadTableFromResourcePath:@"/empty/array" usingBlock:^(RKObjectLoader *objectLoader) { + objectLoader.objectMapping = [RKObjectMapping mappingForClass:[RKTestUser class] usingBlock:^(RKObjectMapping *mapping) { [mapping mapAttributes:@"name", nil]; }]; }]; @@ -861,22 +922,23 @@ - (void)testNotifyTheDelegateWhenAnEmptyCollectionIsLoaded { STAssertNoThrow([mockDelegate verify], nil); } -- (void)testNotifyTheDelegateWhenModelWillLoadWithObjectLoader { - RKObjectManager* objectManager = [RKTestFactory objectManager]; - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testNotifyTheDelegateWhenModelWillLoadWithObjectLoader +{ + RKObjectManager *objectManager = [RKTestFactory objectManager]; + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; tableController.objectManager = objectManager; - [tableController mapObjectsWithClass:[RKTestUser class] toTableCellsWithMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* mapping) { + [tableController mapObjectsWithClass:[RKTestUser class] toTableCellsWithMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *mapping) { mapping.cellClass = [RKTestUserTableViewCell class]; [mapping mapKeyPath:@"name" toAttribute:@"textLabel.text"]; [mapping mapKeyPath:@"nickName" toAttribute:@"detailTextLabel.text"]; }]]; - RKTableControllerTestDelegate* delegate = [RKTableControllerTestDelegate new]; + RKTableControllerTestDelegate *delegate = [RKTableControllerTestDelegate new]; id mockDelegate = [OCMockObject partialMockForObject:delegate]; [[[mockDelegate expect] andForwardToRealObject] tableController:tableController willLoadTableWithObjectLoader:OCMOCK_ANY]; tableController.delegate = mockDelegate; - [tableController loadTableFromResourcePath:@"/empty/array" usingBlock:^(RKObjectLoader* objectLoader) { - objectLoader.objectMapping = [RKObjectMapping mappingForClass:[RKTestUser class] usingBlock:^(RKObjectMapping* mapping) { + [tableController loadTableFromResourcePath:@"/empty/array" usingBlock:^(RKObjectLoader *objectLoader) { + objectLoader.objectMapping = [RKObjectMapping mappingForClass:[RKTestUser class] usingBlock:^(RKObjectMapping *mapping) { [mapping mapAttributes:@"name", nil]; }]; }]; @@ -884,22 +946,23 @@ - (void)testNotifyTheDelegateWhenModelWillLoadWithObjectLoader { STAssertNoThrow([mockDelegate verify], nil); } -- (void)testNotifyTheDelegateWhenModelDidLoadWithObjectLoader { - RKObjectManager* objectManager = [RKTestFactory objectManager]; - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testNotifyTheDelegateWhenModelDidLoadWithObjectLoader +{ + RKObjectManager *objectManager = [RKTestFactory objectManager]; + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; tableController.objectManager = objectManager; - [tableController mapObjectsWithClass:[RKTestUser class] toTableCellsWithMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* mapping) { + [tableController mapObjectsWithClass:[RKTestUser class] toTableCellsWithMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *mapping) { mapping.cellClass = [RKTestUserTableViewCell class]; [mapping mapKeyPath:@"name" toAttribute:@"textLabel.text"]; [mapping mapKeyPath:@"nickName" toAttribute:@"detailTextLabel.text"]; }]]; - RKTableControllerTestDelegate* delegate = [RKTableControllerTestDelegate new]; + RKTableControllerTestDelegate *delegate = [RKTableControllerTestDelegate new]; id mockDelegate = [OCMockObject partialMockForObject:delegate]; [[[mockDelegate expect] andForwardToRealObject] tableController:tableController didLoadTableWithObjectLoader:OCMOCK_ANY]; tableController.delegate = mockDelegate; - [tableController loadTableFromResourcePath:@"/empty/array" usingBlock:^(RKObjectLoader* objectLoader) { - objectLoader.objectMapping = [RKObjectMapping mappingForClass:[RKTestUser class] usingBlock:^(RKObjectMapping* mapping) { + [tableController loadTableFromResourcePath:@"/empty/array" usingBlock:^(RKObjectLoader *objectLoader) { + objectLoader.objectMapping = [RKObjectMapping mappingForClass:[RKTestUser class] usingBlock:^(RKObjectMapping *mapping) { [mapping mapAttributes:@"name", nil]; }]; }]; @@ -907,22 +970,23 @@ - (void)testNotifyTheDelegateWhenModelDidLoadWithObjectLoader { STAssertNoThrow([mockDelegate verify], nil); } -- (void)testNotifyTheDelegateWhenModelDidCancelLoad { - RKObjectManager* objectManager = [RKTestFactory objectManager]; - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testNotifyTheDelegateWhenModelDidCancelLoad +{ + RKObjectManager *objectManager = [RKTestFactory objectManager]; + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; tableController.objectManager = objectManager; - [tableController mapObjectsWithClass:[RKTestUser class] toTableCellsWithMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* mapping) { + [tableController mapObjectsWithClass:[RKTestUser class] toTableCellsWithMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *mapping) { mapping.cellClass = [RKTestUserTableViewCell class]; [mapping mapKeyPath:@"name" toAttribute:@"textLabel.text"]; [mapping mapKeyPath:@"nickName" toAttribute:@"detailTextLabel.text"]; }]]; - RKTableControllerTestDelegate* delegate = [RKTableControllerTestDelegate new]; + RKTableControllerTestDelegate *delegate = [RKTableControllerTestDelegate new]; id mockDelegate = [OCMockObject partialMockForObject:delegate]; [[[mockDelegate expect] andForwardToRealObject] tableControllerDidCancelLoad:tableController]; tableController.delegate = mockDelegate; - [tableController loadTableFromResourcePath:@"/empty/array" usingBlock:^(RKObjectLoader* objectLoader) { - objectLoader.objectMapping = [RKObjectMapping mappingForClass:[RKTestUser class] usingBlock:^(RKObjectMapping* mapping) { + [tableController loadTableFromResourcePath:@"/empty/array" usingBlock:^(RKObjectLoader *objectLoader) { + objectLoader.objectMapping = [RKObjectMapping mappingForClass:[RKTestUser class] usingBlock:^(RKObjectMapping *mapping) { [mapping mapAttributes:@"name", nil]; }]; }]; @@ -930,11 +994,12 @@ - (void)testNotifyTheDelegateWhenModelDidCancelLoad { STAssertNoThrow([mockDelegate verify], nil); } -- (void)testNotifyTheDelegateWhenDidEndEditingARow { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; - RKTableItem* tableItem = [RKTableItem tableItem]; - RKTableControllerTestDelegate* delegate = [RKTableControllerTestDelegate new]; +- (void)testNotifyTheDelegateWhenDidEndEditingARow +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; + RKTableItem *tableItem = [RKTableItem tableItem]; + RKTableControllerTestDelegate *delegate = [RKTableControllerTestDelegate new]; id mockDelegate = [OCMockObject partialMockForObject:delegate]; [[[mockDelegate expect] andForwardToRealObject] tableController:tableController didEndEditing:OCMOCK_ANY @@ -945,11 +1010,12 @@ - (void)testNotifyTheDelegateWhenDidEndEditingARow { STAssertNoThrow([mockDelegate verify], nil); } -- (void)testNotifyTheDelegateWhenWillBeginEditingARow { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; - RKTableItem* tableItem = [RKTableItem tableItem]; - RKTableControllerTestDelegate* delegate = [RKTableControllerTestDelegate new]; +- (void)testNotifyTheDelegateWhenWillBeginEditingARow +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; + RKTableItem *tableItem = [RKTableItem tableItem]; + RKTableControllerTestDelegate *delegate = [RKTableControllerTestDelegate new]; id mockDelegate = [OCMockObject partialMockForObject:delegate]; [[[mockDelegate expect] andForwardToRealObject] tableController:tableController willBeginEditing:OCMOCK_ANY @@ -960,11 +1026,12 @@ - (void)testNotifyTheDelegateWhenWillBeginEditingARow { STAssertNoThrow([mockDelegate verify], nil); } -- (void)testNotifyTheDelegateWhenAnObjectIsInserted { - NSArray* objects = [NSArray arrayWithObject:@"first object"]; - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; - RKTableControllerTestDelegate* delegate = [RKTableControllerTestDelegate new]; +- (void)testNotifyTheDelegateWhenAnObjectIsInserted +{ + NSArray *objects = [NSArray arrayWithObject:@"first object"]; + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; + RKTableControllerTestDelegate *delegate = [RKTableControllerTestDelegate new]; id mockDelegate = [OCMockObject partialMockForObject:delegate]; [[[mockDelegate expect] andForwardToRealObject] tableController:tableController didInsertObject:@"first object" @@ -982,11 +1049,12 @@ - (void)testNotifyTheDelegateWhenAnObjectIsInserted { STAssertNoThrow([mockDelegate verify], nil); } -- (void)testNotifyTheDelegateWhenAnObjectIsUpdated { - NSArray* objects = [NSArray arrayWithObjects:@"first object", @"second object", nil]; - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; - RKTableControllerTestDelegate* delegate = [RKTableControllerTestDelegate new]; +- (void)testNotifyTheDelegateWhenAnObjectIsUpdated +{ + NSArray *objects = [NSArray arrayWithObjects:@"first object", @"second object", nil]; + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; + RKTableControllerTestDelegate *delegate = [RKTableControllerTestDelegate new]; id mockDelegate = [OCMockObject partialMockForObject:delegate]; [[[mockDelegate expect] andForwardToRealObject] tableController:tableController didInsertObject:@"first object" @@ -1006,11 +1074,12 @@ - (void)testNotifyTheDelegateWhenAnObjectIsUpdated { STAssertNoThrow([mockDelegate verify], nil); } -- (void)testNotifyTheDelegateWhenAnObjectIsDeleted { - NSArray* objects = [NSArray arrayWithObjects:@"first object", @"second object", nil]; - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; - RKTableControllerTestDelegate* delegate = [RKTableControllerTestDelegate new]; +- (void)testNotifyTheDelegateWhenAnObjectIsDeleted +{ + NSArray *objects = [NSArray arrayWithObjects:@"first object", @"second object", nil]; + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; + RKTableControllerTestDelegate *delegate = [RKTableControllerTestDelegate new]; id mockDelegate = [OCMockObject partialMockForObject:delegate]; [[[mockDelegate expect] andForwardToRealObject] tableController:tableController didInsertObject:@"first object" @@ -1030,24 +1099,25 @@ - (void)testNotifyTheDelegateWhenAnObjectIsDeleted { STAssertNoThrow([mockDelegate verify], nil); } -- (void)testNotifyTheDelegateWhenObjectsAreLoadedInASection { - RKObjectManager* objectManager = [RKTestFactory objectManager]; - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testNotifyTheDelegateWhenObjectsAreLoadedInASection +{ + RKObjectManager *objectManager = [RKTestFactory objectManager]; + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; tableController.objectManager = objectManager; - [tableController mapObjectsWithClass:[RKTestUser class] toTableCellsWithMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* mapping) { + [tableController mapObjectsWithClass:[RKTestUser class] toTableCellsWithMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *mapping) { mapping.cellClass = [RKTestUserTableViewCell class]; [mapping mapKeyPath:@"name" toAttribute:@"textLabel.text"]; [mapping mapKeyPath:@"nickName" toAttribute:@"detailTextLabel.text"]; }]]; - - RKTableControllerTestDelegate* delegate = [RKTableControllerTestDelegate new]; + + RKTableControllerTestDelegate *delegate = [RKTableControllerTestDelegate new]; id mockDelegate = [OCMockObject partialMockForObject:delegate]; [[mockDelegate expect] tableController:tableController didLoadObjects:OCMOCK_ANY inSection:OCMOCK_ANY]; tableController.delegate = mockDelegate; - - [tableController loadTableFromResourcePath:@"/JSON/users.json" usingBlock:^(RKObjectLoader* objectLoader) { - objectLoader.objectMapping = [RKObjectMapping mappingForClass:[RKTestUser class] usingBlock:^(RKObjectMapping* mapping) { + + [tableController loadTableFromResourcePath:@"/JSON/users.json" usingBlock:^(RKObjectLoader *objectLoader) { + objectLoader.objectMapping = [RKObjectMapping mappingForClass:[RKTestUser class] usingBlock:^(RKObjectMapping *mapping) { [mapping mapAttributes:@"name", nil]; }]; }]; @@ -1055,21 +1125,22 @@ - (void)testNotifyTheDelegateWhenObjectsAreLoadedInASection { STAssertNoThrow([mockDelegate verify], nil); } -- (void)testDelegateIsNotifiedOfWillDisplayCellForObjectAtIndexPath { - RKObjectManager* objectManager = [RKTestFactory objectManager]; - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testDelegateIsNotifiedOfWillDisplayCellForObjectAtIndexPath +{ + RKObjectManager *objectManager = [RKTestFactory objectManager]; + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; tableController.objectManager = objectManager; - [tableController mapObjectsWithClass:[RKTestUser class] toTableCellsWithMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* mapping) { + [tableController mapObjectsWithClass:[RKTestUser class] toTableCellsWithMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *mapping) { mapping.cellClass = [RKTestUserTableViewCell class]; [mapping mapKeyPath:@"name" toAttribute:@"textLabel.text"]; }]]; - RKTableControllerTestDelegate* delegate = [RKTableControllerTestDelegate new]; + RKTableControllerTestDelegate *delegate = [RKTableControllerTestDelegate new]; id mockDelegate = [OCMockObject partialMockForObject:delegate]; [[[mockDelegate expect] andForwardToRealObject] tableController:tableController willLoadTableWithObjectLoader:OCMOCK_ANY]; tableController.delegate = mockDelegate; - [tableController loadTableFromResourcePath:@"/JSON/users.json" usingBlock:^(RKObjectLoader* objectLoader) { - objectLoader.objectMapping = [RKObjectMapping mappingForClass:[RKTestUser class] usingBlock:^(RKObjectMapping* mapping) { + [tableController loadTableFromResourcePath:@"/JSON/users.json" usingBlock:^(RKObjectLoader *objectLoader) { + objectLoader.objectMapping = [RKObjectMapping mappingForClass:[RKTestUser class] usingBlock:^(RKObjectMapping *mapping) { [mapping mapAttributes:@"name", nil]; }]; }]; @@ -1081,21 +1152,22 @@ - (void)testDelegateIsNotifiedOfWillDisplayCellForObjectAtIndexPath { STAssertNoThrow([mockDelegate verify], nil); } -- (void)testDelegateIsNotifiedOfDidSelectRowForObjectAtIndexPath { - RKObjectManager* objectManager = [RKTestFactory objectManager]; - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testDelegateIsNotifiedOfDidSelectRowForObjectAtIndexPath +{ + RKObjectManager *objectManager = [RKTestFactory objectManager]; + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; tableController.objectManager = objectManager; - [tableController mapObjectsWithClass:[RKTestUser class] toTableCellsWithMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* mapping) { + [tableController mapObjectsWithClass:[RKTestUser class] toTableCellsWithMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *mapping) { mapping.cellClass = [RKTestUserTableViewCell class]; [mapping mapKeyPath:@"name" toAttribute:@"textLabel.text"]; }]]; - RKTableControllerTestDelegate* delegate = [RKTableControllerTestDelegate new]; + RKTableControllerTestDelegate *delegate = [RKTableControllerTestDelegate new]; id mockDelegate = [OCMockObject partialMockForObject:delegate]; [[[mockDelegate expect] andForwardToRealObject] tableController:tableController willLoadTableWithObjectLoader:OCMOCK_ANY]; tableController.delegate = mockDelegate; - [tableController loadTableFromResourcePath:@"/JSON/users.json" usingBlock:^(RKObjectLoader* objectLoader) { - objectLoader.objectMapping = [RKObjectMapping mappingForClass:[RKTestUser class] usingBlock:^(RKObjectMapping* mapping) { + [tableController loadTableFromResourcePath:@"/JSON/users.json" usingBlock:^(RKObjectLoader *objectLoader) { + objectLoader.objectMapping = [RKObjectMapping mappingForClass:[RKTestUser class] usingBlock:^(RKObjectMapping *mapping) { [mapping mapAttributes:@"name", nil]; }]; }]; @@ -1108,12 +1180,13 @@ - (void)testDelegateIsNotifiedOfDidSelectRowForObjectAtIndexPath { #pragma mark - Notifications -- (void)testPostANotificationWhenLoadingStarts { - RKObjectManager* objectManager = [RKTestFactory objectManager]; - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testPostANotificationWhenLoadingStarts +{ + RKObjectManager *objectManager = [RKTestFactory objectManager]; + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; tableController.objectManager = objectManager; - [tableController mapObjectsWithClass:[RKTestUser class] toTableCellsWithMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* mapping) { + [tableController mapObjectsWithClass:[RKTestUser class] toTableCellsWithMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *mapping) { mapping.cellClass = [RKTestUserTableViewCell class]; [mapping mapKeyPath:@"name" toAttribute:@"textLabel.text"]; [mapping mapKeyPath:@"nickName" toAttribute:@"detailTextLabel.text"]; @@ -1121,10 +1194,10 @@ - (void)testPostANotificationWhenLoadingStarts { id observerMock = [OCMockObject observerMock]; [[NSNotificationCenter defaultCenter] addMockObserver:observerMock name:RKTableControllerDidStartLoadNotification object:tableController]; [[observerMock expect] notificationWithName:RKTableControllerDidStartLoadNotification object:tableController]; - RKTableControllerTestDelegate* delegate = [RKTableControllerTestDelegate new]; + RKTableControllerTestDelegate *delegate = [RKTableControllerTestDelegate new]; tableController.delegate = delegate; - [tableController loadTableFromResourcePath:@"/JSON/users.json" usingBlock:^(RKObjectLoader* objectLoader) { - objectLoader.objectMapping = [RKObjectMapping mappingForClass:[RKTestUser class] usingBlock:^(RKObjectMapping* mapping) { + [tableController loadTableFromResourcePath:@"/JSON/users.json" usingBlock:^(RKObjectLoader *objectLoader) { + objectLoader.objectMapping = [RKObjectMapping mappingForClass:[RKTestUser class] usingBlock:^(RKObjectMapping *mapping) { [mapping mapAttributes:@"name", nil]; }]; }]; @@ -1132,12 +1205,13 @@ - (void)testPostANotificationWhenLoadingStarts { [observerMock verify]; } -- (void)testPostANotificationWhenLoadingFinishes { - RKObjectManager* objectManager = [RKTestFactory objectManager]; - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testPostANotificationWhenLoadingFinishes +{ + RKObjectManager *objectManager = [RKTestFactory objectManager]; + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; tableController.objectManager = objectManager; - [tableController mapObjectsWithClass:[RKTestUser class] toTableCellsWithMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* mapping) { + [tableController mapObjectsWithClass:[RKTestUser class] toTableCellsWithMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *mapping) { mapping.cellClass = [RKTestUserTableViewCell class]; [mapping mapKeyPath:@"name" toAttribute:@"textLabel.text"]; [mapping mapKeyPath:@"nickName" toAttribute:@"detailTextLabel.text"]; @@ -1146,11 +1220,11 @@ - (void)testPostANotificationWhenLoadingFinishes { id observerMock = [OCMockObject observerMock]; [[NSNotificationCenter defaultCenter] addMockObserver:observerMock name:RKTableControllerDidFinishLoadNotification object:tableController]; [[observerMock expect] notificationWithName:RKTableControllerDidFinishLoadNotification object:tableController]; - RKTableControllerTestDelegate* delegate = [RKTableControllerTestDelegate new]; + RKTableControllerTestDelegate *delegate = [RKTableControllerTestDelegate new]; tableController.delegate = delegate; - [tableController loadTableFromResourcePath:@"/JSON/users.json" usingBlock:^(RKObjectLoader* objectLoader) { - objectLoader.objectMapping = [RKObjectMapping mappingForClass:[RKTestUser class] usingBlock:^(RKObjectMapping* mapping) { + [tableController loadTableFromResourcePath:@"/JSON/users.json" usingBlock:^(RKObjectLoader *objectLoader) { + objectLoader.objectMapping = [RKObjectMapping mappingForClass:[RKTestUser class] usingBlock:^(RKObjectMapping *mapping) { [mapping mapAttributes:@"name", nil]; }]; }]; @@ -1158,25 +1232,26 @@ - (void)testPostANotificationWhenLoadingFinishes { [observerMock verify]; } -- (void)testPostANotificationWhenObjectsAreLoaded { - RKObjectManager* objectManager = [RKTestFactory objectManager]; - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testPostANotificationWhenObjectsAreLoaded +{ + RKObjectManager *objectManager = [RKTestFactory objectManager]; + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; tableController.objectManager = objectManager; - [tableController mapObjectsWithClass:[RKTestUser class] toTableCellsWithMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* mapping) { + [tableController mapObjectsWithClass:[RKTestUser class] toTableCellsWithMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *mapping) { mapping.cellClass = [RKTestUserTableViewCell class]; [mapping mapKeyPath:@"name" toAttribute:@"textLabel.text"]; [mapping mapKeyPath:@"nickName" toAttribute:@"detailTextLabel.text"]; }]]; - + id observerMock = [OCMockObject observerMock]; [[NSNotificationCenter defaultCenter] addMockObserver:observerMock name:RKTableControllerDidLoadObjectsNotification object:tableController]; [[observerMock expect] notificationWithName:RKTableControllerDidLoadObjectsNotification object:tableController]; - RKTableControllerTestDelegate* delegate = [RKTableControllerTestDelegate new]; + RKTableControllerTestDelegate *delegate = [RKTableControllerTestDelegate new]; tableController.delegate = delegate; - - [tableController loadTableFromResourcePath:@"/JSON/users.json" usingBlock:^(RKObjectLoader* objectLoader) { - objectLoader.objectMapping = [RKObjectMapping mappingForClass:[RKTestUser class] usingBlock:^(RKObjectMapping* mapping) { + + [tableController loadTableFromResourcePath:@"/JSON/users.json" usingBlock:^(RKObjectLoader *objectLoader) { + objectLoader.objectMapping = [RKObjectMapping mappingForClass:[RKTestUser class] usingBlock:^(RKObjectMapping *mapping) { [mapping mapAttributes:@"name", nil]; }]; }]; @@ -1184,12 +1259,13 @@ - (void)testPostANotificationWhenObjectsAreLoaded { [observerMock verify]; } -- (void)testPostANotificationWhenAnErrorOccurs { - RKObjectManager* objectManager = [RKTestFactory objectManager]; - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testPostANotificationWhenAnErrorOccurs +{ + RKObjectManager *objectManager = [RKTestFactory objectManager]; + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; tableController.objectManager = objectManager; - [tableController mapObjectsWithClass:[RKTestUser class] toTableCellsWithMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* mapping) { + [tableController mapObjectsWithClass:[RKTestUser class] toTableCellsWithMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *mapping) { mapping.cellClass = [RKTestUserTableViewCell class]; [mapping mapKeyPath:@"name" toAttribute:@"textLabel.text"]; [mapping mapKeyPath:@"nickName" toAttribute:@"detailTextLabel.text"]; @@ -1198,11 +1274,11 @@ - (void)testPostANotificationWhenAnErrorOccurs { id observerMock = [OCMockObject observerMock]; [[NSNotificationCenter defaultCenter] addMockObserver:observerMock name:RKTableControllerDidLoadErrorNotification object:tableController]; [[observerMock expect] notificationWithName:RKTableControllerDidLoadErrorNotification object:tableController userInfo:OCMOCK_ANY]; - RKTableControllerTestDelegate* delegate = [RKTableControllerTestDelegate new]; + RKTableControllerTestDelegate *delegate = [RKTableControllerTestDelegate new]; tableController.delegate = delegate; - [tableController loadTableFromResourcePath:@"/fail" usingBlock:^(RKObjectLoader* objectLoader) { - objectLoader.objectMapping = [RKObjectMapping mappingForClass:[RKTestUser class] usingBlock:^(RKObjectMapping* mapping) { + [tableController loadTableFromResourcePath:@"/fail" usingBlock:^(RKObjectLoader *objectLoader) { + objectLoader.objectMapping = [RKObjectMapping mappingForClass:[RKTestUser class] usingBlock:^(RKObjectMapping *mapping) { [mapping mapAttributes:@"name", nil]; }]; }]; @@ -1210,13 +1286,14 @@ - (void)testPostANotificationWhenAnErrorOccurs { [observerMock verify]; } -- (void)testPostANotificationWhenAnEmptyCollectionIsLoaded { - RKObjectManager* objectManager = [RKTestFactory objectManager]; +- (void)testPostANotificationWhenAnEmptyCollectionIsLoaded +{ + RKObjectManager *objectManager = [RKTestFactory objectManager]; objectManager.client.cachePolicy = RKRequestCachePolicyNone; - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; tableController.objectManager = objectManager; - [tableController mapObjectsWithClass:[RKTestUser class] toTableCellsWithMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* mapping) { + [tableController mapObjectsWithClass:[RKTestUser class] toTableCellsWithMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *mapping) { mapping.cellClass = [RKTestUserTableViewCell class]; [mapping mapKeyPath:@"name" toAttribute:@"textLabel.text"]; [mapping mapKeyPath:@"nickName" toAttribute:@"detailTextLabel.text"]; @@ -1225,10 +1302,10 @@ - (void)testPostANotificationWhenAnEmptyCollectionIsLoaded { id observerMock = [OCMockObject observerMock]; [[NSNotificationCenter defaultCenter] addMockObserver:observerMock name:RKTableControllerDidLoadEmptyNotification object:tableController]; [[observerMock expect] notificationWithName:RKTableControllerDidLoadEmptyNotification object:tableController]; - RKTableControllerTestDelegate* delegate = [RKTableControllerTestDelegate new]; + RKTableControllerTestDelegate *delegate = [RKTableControllerTestDelegate new]; tableController.delegate = delegate; - [tableController loadTableFromResourcePath:@"/empty/array" usingBlock:^(RKObjectLoader* objectLoader) { - objectLoader.objectMapping = [RKObjectMapping mappingForClass:[RKTestUser class] usingBlock:^(RKObjectMapping* mapping) { + [tableController loadTableFromResourcePath:@"/empty/array" usingBlock:^(RKObjectLoader *objectLoader) { + objectLoader.objectMapping = [RKObjectMapping mappingForClass:[RKTestUser class] usingBlock:^(RKObjectMapping *mapping) { [mapping mapAttributes:@"name", nil]; }]; }]; @@ -1238,15 +1315,17 @@ - (void)testPostANotificationWhenAnEmptyCollectionIsLoaded { #pragma mark - State Transitions -- (void)testInitializesToNotYetLoadedState { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testInitializesToNotYetLoadedState +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; assertThatBool(tableController.state == RKTableControllerStateNotYetLoaded, is(equalToBool(YES))); } -- (void)testInitialLoadSetsStateToLoading { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testInitialLoadSetsStateToLoading +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; assertThatBool([tableController isLoaded], is(equalToBool(NO))); assertThatBool([tableController isLoading], is(equalToBool(NO))); id mockLoader = [OCMockObject mockForClass:[RKObjectLoader class]]; @@ -1255,9 +1334,10 @@ - (void)testInitialLoadSetsStateToLoading { assertThatBool([tableController isLoaded], is(equalToBool(NO))); } -- (void)testSuccessfulLoadSetsStateToNormal { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testSuccessfulLoadSetsStateToNormal +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; assertThatBool([tableController isLoaded], is(equalToBool(NO))); assertThatBool([tableController isLoading], is(equalToBool(NO))); id mockLoader = [OCMockObject mockForClass:[RKObjectLoader class]]; @@ -1267,9 +1347,10 @@ - (void)testSuccessfulLoadSetsStateToNormal { assertThatInteger(tableController.state, is(equalToInteger(RKTableControllerStateNormal))); } -- (void)testErrorLoadsSetsStateToError { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testErrorLoadsSetsStateToError +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; assertThatBool([tableController isLoaded], is(equalToBool(NO))); assertThatBool([tableController isLoading], is(equalToBool(NO))); id mockLoader = [OCMockObject mockForClass:[RKObjectLoader class]]; @@ -1280,9 +1361,10 @@ - (void)testErrorLoadsSetsStateToError { assertThatBool([tableController isEmpty], is(equalToBool(YES))); } -- (void)testSecondaryLoadAfterErrorSetsStateToErrorAndLoading { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testSecondaryLoadAfterErrorSetsStateToErrorAndLoading +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; assertThatBool([tableController isLoaded], is(equalToBool(NO))); assertThatBool([tableController isLoading], is(equalToBool(NO))); id mockLoader = [OCMockObject mockForClass:[RKObjectLoader class]]; @@ -1296,16 +1378,18 @@ - (void)testSecondaryLoadAfterErrorSetsStateToErrorAndLoading { assertThatBool([tableController isError], is(equalToBool(YES))); } -- (void)testEmptyLoadSetsStateToEmpty { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testEmptyLoadSetsStateToEmpty +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; [tableController loadEmpty]; assertThatBool([tableController isEmpty], is(equalToBool(YES))); } -- (void)testSecondaryLoadAfterEmptySetsStateToEmptyAndLoading { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testSecondaryLoadAfterEmptySetsStateToEmptyAndLoading +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; [tableController loadEmpty]; assertThatBool([tableController isEmpty], is(equalToBool(YES))); assertThatBool([tableController isLoading], is(equalToBool(NO))); @@ -1315,13 +1399,14 @@ - (void)testSecondaryLoadAfterEmptySetsStateToEmptyAndLoading { assertThatBool([tableController isEmpty], is(equalToBool(YES))); } -- (void)testTransitionToOfflineAfterLoadSetsStateToOfflineAndLoaded { - RKObjectManager* objectManager = [RKTestFactory objectManager]; +- (void)testTransitionToOfflineAfterLoadSetsStateToOfflineAndLoaded +{ + RKObjectManager *objectManager = [RKTestFactory objectManager]; id mockManager = [OCMockObject partialMockForObject:objectManager]; BOOL isOnline = YES; [[[mockManager stub] andReturnValue:OCMOCK_VALUE(isOnline)] isOnline]; - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; tableController.objectManager = mockManager; [tableController loadEmpty]; assertThatBool([tableController isEmpty], is(equalToBool(YES))); @@ -1341,48 +1426,52 @@ - (void)testTransitionToOfflineAfterLoadSetsStateToOfflineAndLoaded { #pragma mark - State Views -- (void)testPermitYouToOverlayAnImageOnTheTable { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; - UIImage* image = [RKTestFixture imageWithContentsOfFixture:@"blake.png"]; +- (void)testPermitYouToOverlayAnImageOnTheTable +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; + UIImage *image = [RKTestFixture imageWithContentsOfFixture:@"blake.png"]; [tableController showImageInOverlay:image]; - UIImageView* imageView = tableController.stateOverlayImageView; + UIImageView *imageView = tableController.stateOverlayImageView; assertThat(imageView, isNot(nilValue())); assertThat(imageView.image, is(equalTo(image))); } -- (void)testPermitYouToRemoveAnImageOverlayFromTheTable { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; - UIImage* image = [RKTestFixture imageWithContentsOfFixture:@"blake.png"]; +- (void)testPermitYouToRemoveAnImageOverlayFromTheTable +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; + UIImage *image = [RKTestFixture imageWithContentsOfFixture:@"blake.png"]; [tableController showImageInOverlay:image]; assertThat([tableController.tableView.superview subviews], isNot(empty())); [tableController removeImageOverlay]; assertThat([tableController.tableView.superview subviews], is(nilValue())); } -- (void)testTriggerDisplayOfTheErrorViewOnTransitionToErrorState { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; - UIImage* image = [RKTestFixture imageWithContentsOfFixture:@"blake.png"]; +- (void)testTriggerDisplayOfTheErrorViewOnTransitionToErrorState +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; + UIImage *image = [RKTestFixture imageWithContentsOfFixture:@"blake.png"]; tableController.imageForError = image; id mockError = [OCMockObject mockForClass:[NSError class]]; [tableController objectLoader:nil didFailWithError:mockError]; assertThatBool([tableController isError], is(equalToBool(YES))); - UIImageView* imageView = tableController.stateOverlayImageView; + UIImageView *imageView = tableController.stateOverlayImageView; assertThat(imageView, isNot(nilValue())); assertThat(imageView.image, is(equalTo(image))); } -- (void)testTriggerHidingOfTheErrorViewOnTransitionOutOfTheErrorState { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; - UIImage* image = [RKTestFixture imageWithContentsOfFixture:@"blake.png"]; +- (void)testTriggerHidingOfTheErrorViewOnTransitionOutOfTheErrorState +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; + UIImage *image = [RKTestFixture imageWithContentsOfFixture:@"blake.png"]; tableController.imageForError = image; id mockError = [OCMockObject niceMockForClass:[NSError class]]; [tableController objectLoader:nil didFailWithError:mockError]; assertThatBool([tableController isError], is(equalToBool(YES))); - UIImageView* imageView = tableController.stateOverlayImageView; + UIImageView *imageView = tableController.stateOverlayImageView; assertThat(imageView, isNot(nilValue())); assertThat(imageView.image, is(equalTo(image))); [tableController loadTableItems:[NSArray arrayWithObject:[RKTableItem tableItem]]]; @@ -1390,49 +1479,53 @@ - (void)testTriggerHidingOfTheErrorViewOnTransitionOutOfTheErrorState { assertThat(tableController.stateOverlayImageView.image, is(nilValue())); } -- (void)testTriggerDisplayOfTheEmptyViewOnTransitionToEmptyState { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; - UIImage* image = [RKTestFixture imageWithContentsOfFixture:@"blake.png"]; +- (void)testTriggerDisplayOfTheEmptyViewOnTransitionToEmptyState +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; + UIImage *image = [RKTestFixture imageWithContentsOfFixture:@"blake.png"]; tableController.imageForEmpty = image; [tableController loadEmpty]; assertThatBool([tableController isEmpty], is(equalToBool(YES))); - UIImageView* imageView = tableController.stateOverlayImageView; + UIImageView *imageView = tableController.stateOverlayImageView; assertThat(imageView, isNot(nilValue())); assertThat(imageView.image, is(equalTo(image))); } -- (void)testTriggerHidingOfTheEmptyViewOnTransitionOutOfTheEmptyState { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; - UIImage* image = [RKTestFixture imageWithContentsOfFixture:@"blake.png"]; +- (void)testTriggerHidingOfTheEmptyViewOnTransitionOutOfTheEmptyState +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; + UIImage *image = [RKTestFixture imageWithContentsOfFixture:@"blake.png"]; tableController.imageForEmpty = image; [tableController loadEmpty]; assertThatBool([tableController isEmpty], is(equalToBool(YES))); - UIImageView* imageView = tableController.stateOverlayImageView; + UIImageView *imageView = tableController.stateOverlayImageView; assertThat(imageView, isNot(nilValue())); assertThat(imageView.image, is(equalTo(image))); [tableController loadTableItems:[NSArray arrayWithObject:[RKTableItem tableItem]]]; assertThat(tableController.stateOverlayImageView.image, is(nilValue())); } -- (void)testTriggerDisplayOfTheLoadingViewOnTransitionToTheLoadingState { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; - UIActivityIndicatorView* spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]; +- (void)testTriggerDisplayOfTheLoadingViewOnTransitionToTheLoadingState +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; + UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]; tableController.loadingView = spinner; [tableController setValue:[NSNumber numberWithBool:YES] forKey:@"loading"]; - UIView* view = [tableController.tableOverlayView.subviews lastObject]; + UIView *view = [tableController.tableOverlayView.subviews lastObject]; assertThatBool(view == spinner, is(equalToBool(YES))); } -- (void)testTriggerHidingOfTheLoadingViewOnTransitionOutOfTheLoadingState { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; - UIActivityIndicatorView* spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]; +- (void)testTriggerHidingOfTheLoadingViewOnTransitionOutOfTheLoadingState +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; + UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]; tableController.loadingView = spinner; [tableController setValue:[NSNumber numberWithBool:YES] forKey:@"loading"]; - UIView* loadingView = [tableController.tableOverlayView.subviews lastObject]; + UIView *loadingView = [tableController.tableOverlayView.subviews lastObject]; assertThatBool(loadingView == spinner, is(equalToBool(YES))); [tableController setValue:[NSNumber numberWithBool:NO] forKey:@"loading"]; loadingView = [tableController.tableOverlayView.subviews lastObject]; @@ -1441,23 +1534,24 @@ - (void)testTriggerHidingOfTheLoadingViewOnTransitionOutOfTheLoadingState { #pragma mark - Header, Footer, and Empty Rows -- (void)testShowHeaderRows { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; - [tableController addHeaderRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { +- (void)testShowHeaderRows +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; + [tableController addHeaderRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Header"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; - NSArray* tableItems = [RKTableItem tableItemsFromStrings:@"One", @"Two", @"Three", nil]; + NSArray *tableItems = [RKTableItem tableItemsFromStrings:@"One", @"Two", @"Three", nil]; [tableController loadTableItems:tableItems]; assertThatBool([tableController isLoaded], is(equalToBool(YES))); assertThatInt(tableController.rowCount, is(equalToInt(4))); - UITableViewCell* cellOne = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; - UITableViewCell* cellTwo = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]]; - UITableViewCell* cellThree = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]]; - UITableViewCell* cellFour = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:3 inSection:0]]; + UITableViewCell *cellOne = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; + UITableViewCell *cellTwo = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]]; + UITableViewCell *cellThree = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]]; + UITableViewCell *cellFour = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:3 inSection:0]]; assertThat(cellOne.textLabel.text, is(equalTo(@"Header"))); assertThat(cellTwo.textLabel.text, is(equalTo(@"One"))); assertThat(cellThree.textLabel.text, is(equalTo(@"Two"))); @@ -1472,23 +1566,24 @@ - (void)testShowHeaderRows { assertThatBool(cellFour.hidden, is(equalToBool(NO))); } -- (void)testShowFooterRows { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; - [tableController addFooterRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { +- (void)testShowFooterRows +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; + [tableController addFooterRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Footer"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; - NSArray* tableItems = [RKTableItem tableItemsFromStrings:@"One", @"Two", @"Three", nil]; + NSArray *tableItems = [RKTableItem tableItemsFromStrings:@"One", @"Two", @"Three", nil]; [tableController loadTableItems:tableItems]; assertThatBool([tableController isLoaded], is(equalToBool(YES))); assertThatInt(tableController.rowCount, is(equalToInt(4))); - UITableViewCell* cellOne = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; - UITableViewCell* cellTwo = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]]; - UITableViewCell* cellThree = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]]; - UITableViewCell* cellFour = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:3 inSection:0]]; + UITableViewCell *cellOne = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; + UITableViewCell *cellTwo = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]]; + UITableViewCell *cellThree = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]]; + UITableViewCell *cellFour = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:3 inSection:0]]; assertThat(cellOne.textLabel.text, is(equalTo(@"One"))); assertThat(cellTwo.textLabel.text, is(equalTo(@"Two"))); assertThat(cellThree.textLabel.text, is(equalTo(@"Three"))); @@ -1503,12 +1598,13 @@ - (void)testShowFooterRows { assertThatBool(cellFour.hidden, is(equalToBool(NO))); } -- (void)testHideHeaderRowsWhenEmptyWhenPropertyIsNotSet { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; - [tableController addHeaderRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { +- (void)testHideHeaderRowsWhenEmptyWhenPropertyIsNotSet +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; + [tableController addHeaderRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Header"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; @@ -1517,18 +1613,19 @@ - (void)testHideHeaderRowsWhenEmptyWhenPropertyIsNotSet { assertThatBool([tableController isLoaded], is(equalToBool(YES))); assertThatInt(tableController.rowCount, is(equalToInt(1))); assertThatBool([tableController isEmpty], is(equalToBool(YES))); - UITableViewCell* cellOne = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; + UITableViewCell *cellOne = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; assertThat(cellOne.textLabel.text, is(equalTo(@"Header"))); [tableController tableView:tableController.tableView willDisplayCell:cellOne forRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; assertThatBool(cellOne.hidden, is(equalToBool(YES))); } -- (void)testHideFooterRowsWhenEmptyWhenPropertyIsNotSet { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; - [tableController addFooterRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { +- (void)testHideFooterRowsWhenEmptyWhenPropertyIsNotSet +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; + [tableController addFooterRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Footer"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; @@ -1537,30 +1634,31 @@ - (void)testHideFooterRowsWhenEmptyWhenPropertyIsNotSet { assertThatBool([tableController isLoaded], is(equalToBool(YES))); assertThatInt(tableController.rowCount, is(equalToInt(1))); assertThatBool([tableController isEmpty], is(equalToBool(YES))); - UITableViewCell* cellOne = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; + UITableViewCell *cellOne = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; assertThat(cellOne.textLabel.text, is(equalTo(@"Footer"))); [tableController tableView:tableController.tableView willDisplayCell:cellOne forRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; assertThatBool(cellOne.hidden, is(equalToBool(YES))); } -- (void)testRemoveHeaderAndFooterCountsWhenDeterminingIsEmpty { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; - [tableController addHeaderRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { +- (void)testRemoveHeaderAndFooterCountsWhenDeterminingIsEmpty +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; + [tableController addHeaderRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Header"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; - [tableController addFooterRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController addFooterRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Footer"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; - [tableController setEmptyItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController setEmptyItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Empty"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; @@ -1572,37 +1670,38 @@ - (void)testRemoveHeaderAndFooterCountsWhenDeterminingIsEmpty { assertThatBool([tableController isEmpty], is(equalToBool(YES))); } -- (void)testNotShowTheEmptyItemWhenTheTableIsNotEmpty { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; - [tableController addHeaderRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { +- (void)testNotShowTheEmptyItemWhenTheTableIsNotEmpty +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; + [tableController addHeaderRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Header"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; - [tableController addFooterRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController addFooterRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Footer"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; - [tableController setEmptyItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController setEmptyItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Empty"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; - NSArray* tableItems = [RKTableItem tableItemsFromStrings:@"One", @"Two", @"Three", nil]; + NSArray *tableItems = [RKTableItem tableItemsFromStrings:@"One", @"Two", @"Three", nil]; [tableController loadTableItems:tableItems]; assertThatBool([tableController isLoaded], is(equalToBool(YES))); assertThatInt(tableController.rowCount, is(equalToInt(6))); - UITableViewCell* cellOne = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; - UITableViewCell* cellTwo = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]]; - UITableViewCell* cellThree = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]]; - UITableViewCell* cellFour = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:3 inSection:0]]; - UITableViewCell* cellFive = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:4 inSection:0]]; - UITableViewCell* cellSix = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:5 inSection:0]]; + UITableViewCell *cellOne = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; + UITableViewCell *cellTwo = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]]; + UITableViewCell *cellThree = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]]; + UITableViewCell *cellFour = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:3 inSection:0]]; + UITableViewCell *cellFive = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:4 inSection:0]]; + UITableViewCell *cellSix = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:5 inSection:0]]; assertThat(cellOne.textLabel.text, is(equalTo(@"Empty"))); assertThat(cellTwo.textLabel.text, is(equalTo(@"Header"))); assertThat(cellThree.textLabel.text, is(equalTo(@"One"))); @@ -1623,24 +1722,25 @@ - (void)testNotShowTheEmptyItemWhenTheTableIsNotEmpty { assertThatBool(cellSix.hidden, is(equalToBool(NO))); } -- (void)testShowTheEmptyItemWhenTheTableIsEmpty { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; - [tableController addHeaderRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { +- (void)testShowTheEmptyItemWhenTheTableIsEmpty +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; + [tableController addHeaderRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Header"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; - [tableController addFooterRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController addFooterRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Footer"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; - [tableController setEmptyItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController setEmptyItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Empty"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; @@ -1650,9 +1750,9 @@ - (void)testShowTheEmptyItemWhenTheTableIsEmpty { assertThatBool([tableController isLoaded], is(equalToBool(YES))); assertThatInt(tableController.rowCount, is(equalToInt(3))); assertThatBool([tableController isEmpty], is(equalToBool(YES))); - UITableViewCell* cellOne = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; - UITableViewCell* cellTwo = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]]; - UITableViewCell* cellThree = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]]; + UITableViewCell *cellOne = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; + UITableViewCell *cellTwo = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]]; + UITableViewCell *cellThree = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]]; assertThat(cellOne.textLabel.text, is(equalTo(@"Empty"))); assertThat(cellTwo.textLabel.text, is(equalTo(@"Header"))); assertThat(cellThree.textLabel.text, is(equalTo(@"Footer"))); @@ -1664,24 +1764,25 @@ - (void)testShowTheEmptyItemWhenTheTableIsEmpty { assertThatBool(cellThree.hidden, is(equalToBool(YES))); } -- (void)testShowTheEmptyItemPlusHeadersAndFootersWhenTheTableIsEmpty { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; - [tableController addHeaderRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { +- (void)testShowTheEmptyItemPlusHeadersAndFootersWhenTheTableIsEmpty +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; + [tableController addHeaderRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Header"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; - [tableController addFooterRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController addFooterRowForItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Footer"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; - [tableController setEmptyItem:[RKTableItem tableItemUsingBlock:^(RKTableItem* tableItem) { + [tableController setEmptyItem:[RKTableItem tableItemUsingBlock:^(RKTableItem *tableItem) { tableItem.text = @"Empty"; - tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + tableItem.cellMapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { [cellMapping addDefaultMappings]; }]; }]]; @@ -1691,9 +1792,9 @@ - (void)testShowTheEmptyItemPlusHeadersAndFootersWhenTheTableIsEmpty { assertThatBool([tableController isLoaded], is(equalToBool(YES))); assertThatInt(tableController.rowCount, is(equalToInt(3))); assertThatBool([tableController isEmpty], is(equalToBool(YES))); - UITableViewCell* cellOne = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; - UITableViewCell* cellTwo = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]]; - UITableViewCell* cellThree = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]]; + UITableViewCell *cellOne = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; + UITableViewCell *cellTwo = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]]; + UITableViewCell *cellThree = [tableController tableView:tableController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]]; assertThat(cellOne.textLabel.text, is(equalTo(@"Empty"))); assertThat(cellTwo.textLabel.text, is(equalTo(@"Header"))); assertThat(cellThree.textLabel.text, is(equalTo(@"Footer"))); @@ -1707,13 +1808,14 @@ - (void)testShowTheEmptyItemPlusHeadersAndFootersWhenTheTableIsEmpty { #pragma mark - UITableViewDelegate Tests -- (void)testInvokeTheOnSelectCellForObjectAtIndexPathBlockHandler { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; - RKTableItem* tableItem = [RKTableItem tableItem]; +- (void)testInvokeTheOnSelectCellForObjectAtIndexPathBlockHandler +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; + RKTableItem *tableItem = [RKTableItem tableItem]; __block BOOL dispatched = NO; - [tableController loadTableItems:[NSArray arrayWithObject:tableItem] withMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { - cellMapping.onSelectCellForObjectAtIndexPath = ^(UITableViewCell* cell, id object, NSIndexPath* indexPath) { + [tableController loadTableItems:[NSArray arrayWithObject:tableItem] withMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { + cellMapping.onSelectCellForObjectAtIndexPath = ^(UITableViewCell *cell, id object, NSIndexPath *indexPath) { dispatched = YES; }; }]]; @@ -1721,13 +1823,14 @@ - (void)testInvokeTheOnSelectCellForObjectAtIndexPathBlockHandler { assertThatBool(dispatched, is(equalToBool(YES))); } -- (void)testInvokeTheOnCellWillAppearForObjectAtIndexPathBlockHandler { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; - RKTableItem* tableItem = [RKTableItem tableItem]; +- (void)testInvokeTheOnCellWillAppearForObjectAtIndexPathBlockHandler +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; + RKTableItem *tableItem = [RKTableItem tableItem]; __block BOOL dispatched = NO; - [tableController loadTableItems:[NSArray arrayWithObject:tableItem] withMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { - cellMapping.onCellWillAppearForObjectAtIndexPath = ^(UITableViewCell* cell, id object, NSIndexPath* indexPath) { + [tableController loadTableItems:[NSArray arrayWithObject:tableItem] withMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { + cellMapping.onCellWillAppearForObjectAtIndexPath = ^(UITableViewCell *cell, id object, NSIndexPath *indexPath) { dispatched = YES; }; }]]; @@ -1736,11 +1839,12 @@ - (void)testInvokeTheOnCellWillAppearForObjectAtIndexPathBlockHandler { assertThatBool(dispatched, is(equalToBool(YES))); } -- (void)testOptionallyHideHeaderRowsWhenTheyAppearAndTheTableIsEmpty { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testOptionallyHideHeaderRowsWhenTheyAppearAndTheTableIsEmpty +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; tableController.showsHeaderRowsWhenEmpty = NO; - RKTableItem* tableItem = [RKTableItem tableItem]; + RKTableItem *tableItem = [RKTableItem tableItem]; [tableController addHeaderRowForItem:tableItem]; [tableController loadEmpty]; id mockCell = [OCMockObject niceMockForClass:[UITableViewCell class]]; @@ -1749,11 +1853,12 @@ - (void)testOptionallyHideHeaderRowsWhenTheyAppearAndTheTableIsEmpty { [mockCell verify]; } -- (void)testOptionallyHideFooterRowsWhenTheyAppearAndTheTableIsEmpty { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testOptionallyHideFooterRowsWhenTheyAppearAndTheTableIsEmpty +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; tableController.showsFooterRowsWhenEmpty = NO; - RKTableItem* tableItem = [RKTableItem tableItem]; + RKTableItem *tableItem = [RKTableItem tableItem]; [tableController addFooterRowForItem:tableItem]; [tableController loadEmpty]; id mockCell = [OCMockObject niceMockForClass:[UITableViewCell class]]; @@ -1762,13 +1867,14 @@ - (void)testOptionallyHideFooterRowsWhenTheyAppearAndTheTableIsEmpty { [mockCell verify]; } -- (void)testInvokeABlockCallbackWhenTheCellAccessoryButtonIsTapped { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; - RKTableItem* tableItem = [RKTableItem tableItem]; +- (void)testInvokeABlockCallbackWhenTheCellAccessoryButtonIsTapped +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; + RKTableItem *tableItem = [RKTableItem tableItem]; __block BOOL dispatched = NO; RKTableViewCellMapping *mapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { - cellMapping.onTapAccessoryButtonForObjectAtIndexPath = ^(UITableViewCell* cell, id object, NSIndexPath* indexPath) { + cellMapping.onTapAccessoryButtonForObjectAtIndexPath = ^(UITableViewCell *cell, id object, NSIndexPath *indexPath) { dispatched = YES; }; }]; @@ -1777,29 +1883,31 @@ - (void)testInvokeABlockCallbackWhenTheCellAccessoryButtonIsTapped { assertThatBool(dispatched, is(equalToBool(YES))); } -- (void)testInvokeABlockCallbackWhenTheDeleteConfirmationButtonTitleIsDetermined { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; - RKTableItem* tableItem = [RKTableItem tableItem]; - NSString* deleteTitle = @"Delete Me"; +- (void)testInvokeABlockCallbackWhenTheDeleteConfirmationButtonTitleIsDetermined +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; + RKTableItem *tableItem = [RKTableItem tableItem]; + NSString *deleteTitle = @"Delete Me"; RKTableViewCellMapping *mapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { - cellMapping.titleForDeleteButtonForObjectAtIndexPath = ^ NSString*(UITableViewCell* cell, id object, NSIndexPath* indexPath) { + cellMapping.titleForDeleteButtonForObjectAtIndexPath = ^ NSString*(UITableViewCell *cell, id object, NSIndexPath *indexPath) { return deleteTitle; }; }]; [tableController loadTableItems:[NSArray arrayWithObject:tableItem] withMapping:mapping]; - NSString* delegateTitle = [tableController tableView:tableController.tableView + NSString *delegateTitle = [tableController tableView:tableController.tableView titleForDeleteConfirmationButtonForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; assertThat(delegateTitle, is(equalTo(deleteTitle))); } -- (void)testInvokeABlockCallbackWhenCellEditingStyleIsDetermined { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testInvokeABlockCallbackWhenCellEditingStyleIsDetermined +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; tableController.canEditRows = YES; - RKTableItem* tableItem = [RKTableItem tableItem]; + RKTableItem *tableItem = [RKTableItem tableItem]; RKTableViewCellMapping *mapping = [RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { - cellMapping.editingStyleForObjectAtIndexPath = ^ UITableViewCellEditingStyle(UITableViewCell* cell, id object, NSIndexPath* indexPath) { + cellMapping.editingStyleForObjectAtIndexPath = ^ UITableViewCellEditingStyle(UITableViewCell *cell, id object, NSIndexPath *indexPath) { return UITableViewCellEditingStyleInsert; }; }]; @@ -1809,59 +1917,63 @@ - (void)testInvokeABlockCallbackWhenCellEditingStyleIsDetermined { assertThatInt(delegateStyle, is(equalToInt(UITableViewCellEditingStyleInsert))); } -- (void)testInvokeABlockCallbackWhenACellIsMoved { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testInvokeABlockCallbackWhenACellIsMoved +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; tableController.canMoveRows = YES; - RKTableItem* tableItem = [RKTableItem tableItem]; - NSIndexPath* moveToIndexPath = [NSIndexPath indexPathForRow:2 inSection:0]; - [tableController loadTableItems:[NSArray arrayWithObject:tableItem] withMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { - cellMapping.targetIndexPathForMove = ^ NSIndexPath*(UITableViewCell* cell, id object, NSIndexPath* sourceIndexPath, NSIndexPath* destinationIndexPath) { + RKTableItem *tableItem = [RKTableItem tableItem]; + NSIndexPath *moveToIndexPath = [NSIndexPath indexPathForRow:2 inSection:0]; + [tableController loadTableItems:[NSArray arrayWithObject:tableItem] withMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { + cellMapping.targetIndexPathForMove = ^ NSIndexPath*(UITableViewCell *cell, id object, NSIndexPath *sourceIndexPath, NSIndexPath *destinationIndexPath) { return moveToIndexPath; }; }]]; - NSIndexPath* delegateIndexPath = [tableController tableView:tableController.tableView - targetIndexPathForMoveFromRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]toProposedIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]]; + NSIndexPath *delegateIndexPath = [tableController tableView:tableController.tableView + targetIndexPathForMoveFromRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] toProposedIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]]; assertThat(delegateIndexPath, is(equalTo(moveToIndexPath))); } #pragma mark Variable Height Rows -- (void)testReturnTheRowHeightConfiguredOnTheTableViewWhenVariableHeightRowsIsDisabled { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testReturnTheRowHeightConfiguredOnTheTableViewWhenVariableHeightRowsIsDisabled +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; tableController.variableHeightRows = NO; tableController.tableView.rowHeight = 55; - RKTableItem* tableItem = [RKTableItem tableItem]; - [tableController loadTableItems:[NSArray arrayWithObject:tableItem] withMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + RKTableItem *tableItem = [RKTableItem tableItem]; + [tableController loadTableItems:[NSArray arrayWithObject:tableItem] withMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { cellMapping.rowHeight = 200; }]]; CGFloat height = [tableController tableView:tableController.tableView heightForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; assertThatFloat(height, is(equalToFloat(55))); } -- (void)testReturnTheHeightFromTheTableCellMappingWhenVariableHeightRowsAreEnabled { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testReturnTheHeightFromTheTableCellMappingWhenVariableHeightRowsAreEnabled +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; tableController.variableHeightRows = YES; tableController.tableView.rowHeight = 55; - RKTableItem* tableItem = [RKTableItem tableItem]; - [tableController loadTableItems:[NSArray arrayWithObject:tableItem] withMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + RKTableItem *tableItem = [RKTableItem tableItem]; + [tableController loadTableItems:[NSArray arrayWithObject:tableItem] withMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { cellMapping.rowHeight = 200; }]]; CGFloat height = [tableController tableView:tableController.tableView heightForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; assertThatFloat(height, is(equalToFloat(200))); } -- (void)testInvokeAnBlockCallbackToDetermineTheCellHeightWhenVariableHeightRowsAreEnabled { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testInvokeAnBlockCallbackToDetermineTheCellHeightWhenVariableHeightRowsAreEnabled +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; tableController.variableHeightRows = YES; tableController.tableView.rowHeight = 55; - RKTableItem* tableItem = [RKTableItem tableItem]; - [tableController loadTableItems:[NSArray arrayWithObject:tableItem] withMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping* cellMapping) { + RKTableItem *tableItem = [RKTableItem tableItem]; + [tableController loadTableItems:[NSArray arrayWithObject:tableItem] withMapping:[RKTableViewCellMapping cellMappingUsingBlock:^(RKTableViewCellMapping *cellMapping) { cellMapping.rowHeight = 200; - cellMapping.heightOfCellForObjectAtIndexPath = ^ CGFloat(id object, NSIndexPath* indexPath) { return 150; }; + cellMapping.heightOfCellForObjectAtIndexPath = ^ CGFloat(id object, NSIndexPath *indexPath) { return 150; }; }]]; CGFloat height = [tableController tableView:tableController.tableView heightForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; assertThatFloat(height, is(equalToFloat(150))); @@ -1869,20 +1981,22 @@ - (void)testInvokeAnBlockCallbackToDetermineTheCellHeightWhenVariableHeightRowsA #pragma mark - Editing -- (void)testAllowEditingWhenTheCanEditRowsPropertyIsSet { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testAllowEditingWhenTheCanEditRowsPropertyIsSet +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; tableController.canEditRows = YES; - RKTableItem* tableItem = [RKTableItem tableItem]; + RKTableItem *tableItem = [RKTableItem tableItem]; [tableController loadTableItems:[NSArray arrayWithObject:tableItem]]; BOOL delegateCanEdit = [tableController tableView:tableController.tableView canEditRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; assertThatBool(delegateCanEdit, is(equalToBool(YES))); } -- (void)testCommitADeletionWhenTheCanEditRowsPropertyIsSet { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testCommitADeletionWhenTheCanEditRowsPropertyIsSet +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; tableController.canEditRows = YES; [tableController loadObjects:[NSArray arrayWithObjects:@"First Object", @"Second Object", nil]]; assertThatInt([tableController rowCount], is(equalToInt(2))); @@ -1897,9 +2011,10 @@ - (void)testCommitADeletionWhenTheCanEditRowsPropertyIsSet { is(equalTo(@"First Object"))); } -- (void)testNotCommitADeletionWhenTheCanEditRowsPropertyIsNotSet { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testNotCommitADeletionWhenTheCanEditRowsPropertyIsNotSet +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; [tableController loadObjects:[NSArray arrayWithObjects:@"First Object", @"Second Object", nil]]; assertThatInt([tableController rowCount], is(equalToInt(2))); BOOL delegateCanEdit = [tableController tableView:tableController.tableView @@ -1915,9 +2030,10 @@ - (void)testNotCommitADeletionWhenTheCanEditRowsPropertyIsNotSet { is(equalTo(@"Second Object"))); } -- (void)testDoNothingToCommitAnInsertionWhenTheCanEditRowsPropertyIsSet { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testDoNothingToCommitAnInsertionWhenTheCanEditRowsPropertyIsSet +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; tableController.canEditRows = YES; [tableController loadObjects:[NSArray arrayWithObjects:@"First Object", @"Second Object", nil]]; assertThatInt([tableController rowCount], is(equalToInt(2))); @@ -1934,20 +2050,22 @@ - (void)testDoNothingToCommitAnInsertionWhenTheCanEditRowsPropertyIsSet { is(equalTo(@"Second Object"))); } -- (void)testAllowMovingWhenTheCanMoveRowsPropertyIsSet { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testAllowMovingWhenTheCanMoveRowsPropertyIsSet +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; tableController.canMoveRows = YES; - RKTableItem* tableItem = [RKTableItem tableItem]; + RKTableItem *tableItem = [RKTableItem tableItem]; [tableController loadTableItems:[NSArray arrayWithObject:tableItem]]; BOOL delegateCanMove = [tableController tableView:tableController.tableView canMoveRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; assertThatBool(delegateCanMove, is(equalToBool(YES))); } -- (void)testMoveARowWithinASectionWhenTheCanMoveRowsPropertyIsSet { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testMoveARowWithinASectionWhenTheCanMoveRowsPropertyIsSet +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; tableController.canMoveRows = YES; [tableController loadObjects:[NSArray arrayWithObjects:@"First Object", @"Second Object", nil]]; assertThatInt([tableController rowCount], is(equalToInt(2))); @@ -1964,9 +2082,10 @@ - (void)testMoveARowWithinASectionWhenTheCanMoveRowsPropertyIsSet { is(equalTo(@"Second Object"))); } -- (void)testMoveARowAcrossSectionsWhenTheCanMoveRowsPropertyIsSet { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testMoveARowAcrossSectionsWhenTheCanMoveRowsPropertyIsSet +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; tableController.canMoveRows = YES; [tableController loadObjects:[NSArray arrayWithObjects:@"First Object", @"Second Object", nil]]; assertThatInt([tableController rowCount], is(equalToInt(2))); @@ -1985,9 +2104,10 @@ - (void)testMoveARowAcrossSectionsWhenTheCanMoveRowsPropertyIsSet { is(equalTo(@"Second Object"))); } -- (void)testNotMoveARowWhenTheCanMoveRowsPropertyIsNotSet { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testNotMoveARowWhenTheCanMoveRowsPropertyIsNotSet +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; [tableController loadObjects:[NSArray arrayWithObjects:@"First Object", @"Second Object", nil]]; assertThatInt([tableController rowCount], is(equalToInt(2))); BOOL delegateCanMove = [tableController tableView:tableController.tableView @@ -2005,32 +2125,35 @@ - (void)testNotMoveARowWhenTheCanMoveRowsPropertyIsNotSet { #pragma mark - Reachability Integration -- (void)testTransitionToTheOnlineStateWhenAReachabilityNoticeIsReceived { - RKObjectManager* objectManager = [RKTestFactory objectManager]; +- (void)testTransitionToTheOnlineStateWhenAReachabilityNoticeIsReceived +{ + RKObjectManager *objectManager = [RKTestFactory objectManager]; id mockManager = [OCMockObject partialMockForObject:objectManager]; BOOL online = YES; [[[mockManager stub] andReturnValue:OCMOCK_VALUE(online)] isOnline]; - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; tableController.objectManager = objectManager; [[NSNotificationCenter defaultCenter] postNotificationName:RKObjectManagerDidBecomeOnlineNotification object:objectManager]; assertThatBool(tableController.isOnline, is(equalToBool(YES))); } -- (void)testTransitionToTheOfflineStateWhenAReachabilityNoticeIsReceived { - RKObjectManager* objectManager = [RKTestFactory objectManager]; +- (void)testTransitionToTheOfflineStateWhenAReachabilityNoticeIsReceived +{ + RKObjectManager *objectManager = [RKTestFactory objectManager]; id mockManager = [OCMockObject partialMockForObject:objectManager]; BOOL online = NO; [[[mockManager stub] andReturnValue:OCMOCK_VALUE(online)] isOnline]; - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; tableController.objectManager = objectManager; [[NSNotificationCenter defaultCenter] postNotificationName:RKObjectManagerDidBecomeOfflineNotification object:objectManager]; assertThatBool(tableController.isOnline, is(equalToBool(NO))); } -- (void)testNotifyTheDelegateOnTransitionToOffline { - RKObjectManager* objectManager = [RKTestFactory objectManager]; +- (void)testNotifyTheDelegateOnTransitionToOffline +{ + RKObjectManager *objectManager = [RKTestFactory objectManager]; id mockManager = [OCMockObject partialMockForObject:objectManager]; [mockManager setExpectationOrderMatters:YES]; RKObjectManagerNetworkStatus networkStatus = RKObjectManagerNetworkStatusOnline; @@ -2039,8 +2162,8 @@ - (void)testNotifyTheDelegateOnTransitionToOffline { [[[mockManager expect] andReturnValue:OCMOCK_VALUE(online)] isOnline]; online = NO; // After the notification is posted [[[mockManager expect] andReturnValue:OCMOCK_VALUE(online)] isOnline]; - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; id mockDelegate = [OCMockObject mockForProtocol:@protocol(RKTableControllerDelegate)]; [[mockDelegate expect] tableControllerDidBecomeOffline:tableController]; tableController.delegate = mockDelegate; @@ -2048,8 +2171,9 @@ - (void)testNotifyTheDelegateOnTransitionToOffline { STAssertNoThrow([mockDelegate verify], nil); } -- (void)testPostANotificationOnTransitionToOffline { - RKObjectManager* objectManager = [RKTestFactory objectManager]; +- (void)testPostANotificationOnTransitionToOffline +{ + RKObjectManager *objectManager = [RKTestFactory objectManager]; id mockManager = [OCMockObject partialMockForObject:objectManager]; [mockManager setExpectationOrderMatters:YES]; RKObjectManagerNetworkStatus networkStatus = RKObjectManagerNetworkStatusOnline; @@ -2058,8 +2182,8 @@ - (void)testPostANotificationOnTransitionToOffline { [[[mockManager expect] andReturnValue:OCMOCK_VALUE(online)] isOnline]; online = NO; // After the notification is posted [[[mockManager expect] andReturnValue:OCMOCK_VALUE(online)] isOnline]; - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; id observerMock = [OCMockObject observerMock]; [[NSNotificationCenter defaultCenter] addMockObserver:observerMock name:RKTableControllerDidBecomeOffline object:tableController]; @@ -2069,16 +2193,17 @@ - (void)testPostANotificationOnTransitionToOffline { [observerMock verify]; } -- (void)testNotifyTheDelegateOnTransitionToOnline { - RKObjectManager* objectManager = [RKTestFactory objectManager]; +- (void)testNotifyTheDelegateOnTransitionToOnline +{ + RKObjectManager *objectManager = [RKTestFactory objectManager]; id mockManager = [OCMockObject partialMockForObject:objectManager]; BOOL online = NO; [[[mockManager expect] andReturnValue:OCMOCK_VALUE(online)] isOnline]; online = YES; [[[mockManager stub] andReturnValue:OCMOCK_VALUE(online)] isOnline]; - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; [RKObjectManager setSharedManager:nil]; // Don't want the controller to initialize with the sharedManager... - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; tableController.objectManager = objectManager; id mockDelegate = [OCMockObject mockForProtocol:@protocol(RKTableControllerDelegate)]; [[mockDelegate expect] tableControllerDidBecomeOnline:tableController]; @@ -2088,16 +2213,17 @@ - (void)testNotifyTheDelegateOnTransitionToOnline { STAssertNoThrow([mockDelegate verify], nil); } -- (void)testPostANotificationOnTransitionToOnline { - RKObjectManager* objectManager = [RKTestFactory objectManager]; +- (void)testPostANotificationOnTransitionToOnline +{ + RKObjectManager *objectManager = [RKTestFactory objectManager]; id mockManager = [OCMockObject partialMockForObject:objectManager]; BOOL online = NO; [[[mockManager expect] andReturnValue:OCMOCK_VALUE(online)] isOnline]; online = YES; [[[mockManager stub] andReturnValue:OCMOCK_VALUE(online)] isOnline]; - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; [RKObjectManager setSharedManager:nil]; // Don't want the controller to initialize with the sharedManager... - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; tableController.objectManager = objectManager; id observerMock = [OCMockObject observerMock]; @@ -2108,8 +2234,9 @@ - (void)testPostANotificationOnTransitionToOnline { [observerMock verify]; } -- (void)testShowTheOfflineImageOnTransitionToOffline { - RKObjectManager* objectManager = [RKTestFactory objectManager]; +- (void)testShowTheOfflineImageOnTransitionToOffline +{ + RKObjectManager *objectManager = [RKTestFactory objectManager]; id mockManager = [OCMockObject partialMockForObject:objectManager]; [mockManager setExpectationOrderMatters:YES]; RKObjectManagerNetworkStatus networkStatus = RKObjectManagerNetworkStatusOnline; @@ -2118,20 +2245,21 @@ - (void)testShowTheOfflineImageOnTransitionToOffline { [[[mockManager expect] andReturnValue:OCMOCK_VALUE(online)] isOnline]; online = NO; // After the notification is posted [[[mockManager expect] andReturnValue:OCMOCK_VALUE(online)] isOnline]; - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; - UIImage* image = [RKTestFixture imageWithContentsOfFixture:@"blake.png"]; + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; + UIImage *image = [RKTestFixture imageWithContentsOfFixture:@"blake.png"]; tableController.imageForOffline = image; [[NSNotificationCenter defaultCenter] postNotificationName:RKObjectManagerDidBecomeOfflineNotification object:objectManager]; assertThatBool(tableController.isOnline, is(equalToBool(NO))); - UIImageView* imageView = tableController.stateOverlayImageView; + UIImageView *imageView = tableController.stateOverlayImageView; assertThat(imageView, isNot(nilValue())); assertThat(imageView.image, is(equalTo(image))); } -- (void)testRemoveTheOfflineImageOnTransitionToOnlineFromOffline { - RKObjectManager* objectManager = [RKTestFactory objectManager]; +- (void)testRemoveTheOfflineImageOnTransitionToOnlineFromOffline +{ + RKObjectManager *objectManager = [RKTestFactory objectManager]; id mockManager = [OCMockObject partialMockForObject:objectManager]; [mockManager setExpectationOrderMatters:YES]; RKObjectManagerNetworkStatus networkStatus = RKObjectManagerNetworkStatusOnline; @@ -2140,15 +2268,15 @@ - (void)testRemoveTheOfflineImageOnTransitionToOnlineFromOffline { [[[mockManager expect] andReturnValue:OCMOCK_VALUE(online)] isOnline]; online = NO; // After the notification is posted [[[mockManager expect] andReturnValue:OCMOCK_VALUE(online)] isOnline]; - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; [tableController loadEmpty]; // Load to change the isLoaded state - UIImage* image = [RKTestFixture imageWithContentsOfFixture:@"blake.png"]; + UIImage *image = [RKTestFixture imageWithContentsOfFixture:@"blake.png"]; tableController.imageForOffline = image; [[NSNotificationCenter defaultCenter] postNotificationName:RKObjectManagerDidBecomeOfflineNotification object:objectManager]; assertThatBool(tableController.isOnline, is(equalToBool(NO))); - UIImageView* imageView = tableController.stateOverlayImageView; + UIImageView *imageView = tableController.stateOverlayImageView; assertThat(imageView, isNot(nilValue())); assertThat(imageView.image, is(equalTo(image))); @@ -2162,33 +2290,36 @@ - (void)testRemoveTheOfflineImageOnTransitionToOnlineFromOffline { #pragma mark - Swipe Menus -- (void)testAllowSwipeMenusWhenTheSwipeViewsEnabledPropertyIsSet { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testAllowSwipeMenusWhenTheSwipeViewsEnabledPropertyIsSet +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; tableController.cellSwipeViewsEnabled = YES; - RKTableItem* tableItem = [RKTableItem tableItem]; + RKTableItem *tableItem = [RKTableItem tableItem]; [tableController loadTableItems:[NSArray arrayWithObject:tableItem]]; assertThatBool(tableController.canEditRows, is(equalToBool(NO))); assertThatBool(tableController.cellSwipeViewsEnabled, is(equalToBool(YES))); } -- (void)testNotAllowEditingWhenTheSwipeViewsEnabledPropertyIsSet { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testNotAllowEditingWhenTheSwipeViewsEnabledPropertyIsSet +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; tableController.cellSwipeViewsEnabled = YES; - RKTableItem* tableItem = [RKTableItem tableItem]; + RKTableItem *tableItem = [RKTableItem tableItem]; [tableController loadTableItems:[NSArray arrayWithObject:tableItem]]; BOOL delegateCanEdit = [tableController tableView:tableController.tableView canEditRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; assertThatBool(delegateCanEdit, is(equalToBool(NO))); } -- (void)testRaiseAnExceptionWhenEnablingSwipeViewsWhenTheCanEditRowsPropertyIsSet { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testRaiseAnExceptionWhenEnablingSwipeViewsWhenTheCanEditRowsPropertyIsSet +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; tableController.canEditRows = YES; - NSException* exception = nil; + NSException *exception = nil; @try { tableController.cellSwipeViewsEnabled = YES; } @@ -2200,12 +2331,13 @@ - (void)testRaiseAnExceptionWhenEnablingSwipeViewsWhenTheCanEditRowsPropertyIsSe } } -- (void)testCallTheDelegateBeforeShowingTheSwipeView { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testCallTheDelegateBeforeShowingTheSwipeView +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; tableController.cellSwipeViewsEnabled = YES; - RKTableItem* tableItem = [RKTableItem tableItem]; - RKTableControllerTestDelegate* delegate = [RKTableControllerTestDelegate new]; + RKTableItem *tableItem = [RKTableItem tableItem]; + RKTableControllerTestDelegate *delegate = [RKTableControllerTestDelegate new]; id mockDelegate = [OCMockObject partialMockForObject:delegate]; [[[mockDelegate expect] andForwardToRealObject] tableController:tableController willAddSwipeView:OCMOCK_ANY @@ -2219,12 +2351,13 @@ - (void)testCallTheDelegateBeforeShowingTheSwipeView { STAssertNoThrow([mockDelegate verify], nil); } -- (void)testCallTheDelegateBeforeHidingTheSwipeView { - RKTableControllerTestTableViewController* viewController = [RKTableControllerTestTableViewController new]; - RKTableController* tableController = [RKTableController tableControllerForTableViewController:viewController]; +- (void)testCallTheDelegateBeforeHidingTheSwipeView +{ + RKTableControllerTestTableViewController *viewController = [RKTableControllerTestTableViewController new]; + RKTableController *tableController = [RKTableController tableControllerForTableViewController:viewController]; tableController.cellSwipeViewsEnabled = YES; - RKTableItem* tableItem = [RKTableItem tableItem]; - RKTableControllerTestDelegate* delegate = [RKTableControllerTestDelegate new]; + RKTableItem *tableItem = [RKTableItem tableItem]; + RKTableControllerTestDelegate *delegate = [RKTableControllerTestDelegate new]; id mockDelegate = [OCMockObject partialMockForObject:delegate]; [[[mockDelegate expect] andForwardToRealObject] tableController:tableController willAddSwipeView:OCMOCK_ANY diff --git a/Tests/Application/UI/RKTableViewCellMappingTest.m b/Tests/Application/UI/RKTableViewCellMappingTest.m index bc844d38fc..468ee63316 100644 --- a/Tests/Application/UI/RKTableViewCellMappingTest.m +++ b/Tests/Application/UI/RKTableViewCellMappingTest.m @@ -15,19 +15,23 @@ @interface RKTableViewCellMappingTest : RKTestCase @implementation RKTableViewCellMappingTest -- (void)testCallTheDesignatedInitializerOnUITableViewCell { +- (void)testCallTheDesignatedInitializerOnUITableViewCell +{ } -- (void)testDequeueReusableCells { +- (void)testDequeueReusableCells +{ } -- (void)testSetTheAccessoryType { +- (void)testSetTheAccessoryType +{ } -- (void)testSetTheCellStyle { +- (void)testSetTheCellStyle +{ } diff --git a/Tests/Application/UI/RKTableViewCellMappingsTest.m b/Tests/Application/UI/RKTableViewCellMappingsTest.m index 407cf264c7..98d975c3d6 100644 --- a/Tests/Application/UI/RKTableViewCellMappingsTest.m +++ b/Tests/Application/UI/RKTableViewCellMappingsTest.m @@ -22,12 +22,13 @@ @interface RKTableViewCellMappingsTest : RKTestCase @implementation RKTableViewCellMappingsTest -- (void)testRaiseAnExceptionWhenAnAttemptIsMadeToRegisterAnExistingMappableClass { - RKTableViewCellMappings* cellMappings = [RKTableViewCellMappings cellMappings]; - RKTableViewCellMapping* firstMapping = [RKTableViewCellMapping cellMapping]; - RKTableViewCellMapping* secondMapping = [RKTableViewCellMapping cellMapping]; +- (void)testRaiseAnExceptionWhenAnAttemptIsMadeToRegisterAnExistingMappableClass +{ + RKTableViewCellMappings *cellMappings = [RKTableViewCellMappings cellMappings]; + RKTableViewCellMapping *firstMapping = [RKTableViewCellMapping cellMapping]; + RKTableViewCellMapping *secondMapping = [RKTableViewCellMapping cellMapping]; [cellMappings setCellMapping:firstMapping forClass:[RKTestUser class]]; - NSException* exception = nil; + NSException *exception = nil; @try { [cellMappings setCellMapping:secondMapping forClass:[RKTestUser class]]; } @@ -39,27 +40,30 @@ - (void)testRaiseAnExceptionWhenAnAttemptIsMadeToRegisterAnExistingMappableClass } } -- (void)testFindCellMappingsWithAnExactClassMatch { - RKTableViewCellMappings* cellMappings = [RKTableViewCellMappings cellMappings]; - RKTableViewCellMapping* firstMapping = [RKTableViewCellMapping cellMapping]; - RKTableViewCellMapping* secondMapping = [RKTableViewCellMapping cellMapping]; +- (void)testFindCellMappingsWithAnExactClassMatch +{ + RKTableViewCellMappings *cellMappings = [RKTableViewCellMappings cellMappings]; + RKTableViewCellMapping *firstMapping = [RKTableViewCellMapping cellMapping]; + RKTableViewCellMapping *secondMapping = [RKTableViewCellMapping cellMapping]; [cellMappings setCellMapping:firstMapping forClass:[RKTestSubclassedUser class]]; [cellMappings setCellMapping:secondMapping forClass:[RKTestUser class]]; assertThat([cellMappings cellMappingForObject:[RKTestUser new]], is(equalTo(secondMapping))); } -- (void)testFindCellMappingsWithASubclassMatch { - RKTableViewCellMappings* cellMappings = [RKTableViewCellMappings cellMappings]; - RKTableViewCellMapping* firstMapping = [RKTableViewCellMapping cellMapping]; - RKTableViewCellMapping* secondMapping = [RKTableViewCellMapping cellMapping]; +- (void)testFindCellMappingsWithASubclassMatch +{ + RKTableViewCellMappings *cellMappings = [RKTableViewCellMappings cellMappings]; + RKTableViewCellMapping *firstMapping = [RKTableViewCellMapping cellMapping]; + RKTableViewCellMapping *secondMapping = [RKTableViewCellMapping cellMapping]; [cellMappings setCellMapping:firstMapping forClass:[RKTestUser class]]; [cellMappings setCellMapping:secondMapping forClass:[RKTestSubclassedUser class]]; assertThat([cellMappings cellMappingForObject:[RKTestSubclassedUser new]], is(equalTo(secondMapping))); } -- (void)testReturnTheCellMappingForAnObjectInstance { - RKTableViewCellMappings* cellMappings = [RKTableViewCellMappings cellMappings]; - RKTableViewCellMapping* mapping = [RKTableViewCellMapping cellMapping]; +- (void)testReturnTheCellMappingForAnObjectInstance +{ + RKTableViewCellMappings *cellMappings = [RKTableViewCellMappings cellMappings]; + RKTableViewCellMapping *mapping = [RKTableViewCellMapping cellMapping]; [cellMappings setCellMapping:mapping forClass:[RKTestUser class]]; assertThat([cellMappings cellMappingForObject:[RKTestUser new]], is(equalTo(mapping))); } diff --git a/Tests/Application/UI/RKTableViewSectionTest.m b/Tests/Application/UI/RKTableViewSectionTest.m index 019b017636..b2cd322860 100644 --- a/Tests/Application/UI/RKTableViewSectionTest.m +++ b/Tests/Application/UI/RKTableViewSectionTest.m @@ -18,77 +18,86 @@ @interface RKTableViewSectionTest : RKTestCase @implementation RKTableViewSectionTest -- (void)testInitializeASection { - RKTableSection* section = [RKTableSection section]; +- (void)testInitializeASection +{ + RKTableSection *section = [RKTableSection section]; assertThat(section.objects, is(notNilValue())); assertThat(section.objects, is(empty())); assertThat(section.cellMappings, is(nilValue())); } -- (void)testInitializeASectionWithObjectsAndMappings { - NSArray* objects = [NSArray array]; - RKTableViewCellMappings* mappings = [RKTableViewCellMappings new]; - RKTableSection* section = [RKTableSection sectionForObjects:objects withMappings:mappings]; +- (void)testInitializeASectionWithObjectsAndMappings +{ + NSArray *objects = [NSArray array]; + RKTableViewCellMappings *mappings = [RKTableViewCellMappings new]; + RKTableSection *section = [RKTableSection sectionForObjects:objects withMappings:mappings]; assertThat(section.objects, is(notNilValue())); assertThat(section.cellMappings, isNot(nilValue())); assertThat(section.objects, is(equalTo(objects))); assertThat(section.cellMappings, is(equalTo(mappings))); } -- (void)testMakeAMutableCopyOfTheObjectsItIsInitializedWith { - NSArray* objects = [NSArray array]; - RKTableViewCellMappings* mappings = [RKTableViewCellMappings new]; - RKTableSection* section = [RKTableSection sectionForObjects:objects withMappings:mappings]; +- (void)testMakeAMutableCopyOfTheObjectsItIsInitializedWith +{ + NSArray *objects = [NSArray array]; + RKTableViewCellMappings *mappings = [RKTableViewCellMappings new]; + RKTableSection *section = [RKTableSection sectionForObjects:objects withMappings:mappings]; assertThat(section.objects, is(instanceOf([NSMutableArray class]))); } -- (void)testReturnTheNumberOfRowsInTheSection { - NSArray* objects = [NSArray arrayWithObject:@"first object"]; - RKTableViewCellMappings* mappings = [RKTableViewCellMappings new]; - RKTableSection* section = [RKTableSection sectionForObjects:objects withMappings:mappings]; +- (void)testReturnTheNumberOfRowsInTheSection +{ + NSArray *objects = [NSArray arrayWithObject:@"first object"]; + RKTableViewCellMappings *mappings = [RKTableViewCellMappings new]; + RKTableSection *section = [RKTableSection sectionForObjects:objects withMappings:mappings]; assertThatInt(section.rowCount, is(equalToInt(1))); } -- (void)testReturnTheObjectAtAGivenIndex { - NSArray* objects = [NSArray arrayWithObject:@"first object"]; - RKTableViewCellMappings* mappings = [RKTableViewCellMappings new]; - RKTableSection* section = [RKTableSection sectionForObjects:objects withMappings:mappings]; +- (void)testReturnTheObjectAtAGivenIndex +{ + NSArray *objects = [NSArray arrayWithObject:@"first object"]; + RKTableViewCellMappings *mappings = [RKTableViewCellMappings new]; + RKTableSection *section = [RKTableSection sectionForObjects:objects withMappings:mappings]; assertThat([section objectAtIndex:0], is(equalTo(@"first object"))); } -- (void)testInsertTheObjectAtAGivenIndex { - NSArray* objects = [NSArray arrayWithObject:@"first object"]; - RKTableViewCellMappings* mappings = [RKTableViewCellMappings new]; - RKTableSection* section = [RKTableSection sectionForObjects:objects withMappings:mappings]; +- (void)testInsertTheObjectAtAGivenIndex +{ + NSArray *objects = [NSArray arrayWithObject:@"first object"]; + RKTableViewCellMappings *mappings = [RKTableViewCellMappings new]; + RKTableSection *section = [RKTableSection sectionForObjects:objects withMappings:mappings]; assertThat([section objectAtIndex:0], is(equalTo(@"first object"))); [section insertObject:@"inserted object" atIndex:0]; assertThat([section objectAtIndex:0], is(equalTo(@"inserted object"))); } -- (void)testRemoveTheObjectAtAGivenIndex { - NSArray* objects = [NSArray arrayWithObjects:@"first object", @"second object", nil]; - RKTableViewCellMappings* mappings = [RKTableViewCellMappings new]; - RKTableSection* section = [RKTableSection sectionForObjects:objects withMappings:mappings]; +- (void)testRemoveTheObjectAtAGivenIndex +{ + NSArray *objects = [NSArray arrayWithObjects:@"first object", @"second object", nil]; + RKTableViewCellMappings *mappings = [RKTableViewCellMappings new]; + RKTableSection *section = [RKTableSection sectionForObjects:objects withMappings:mappings]; assertThat([section objectAtIndex:0], is(equalTo(@"first object"))); assertThat([section objectAtIndex:1], is(equalTo(@"second object"))); [section removeObjectAtIndex:0]; assertThat([section objectAtIndex:0], is(equalTo(@"second object"))); } -- (void)testReplaceTheObjectAtAGivenIndex { - NSArray* objects = [NSArray arrayWithObjects:@"first object", @"second object", nil]; - RKTableViewCellMappings* mappings = [RKTableViewCellMappings new]; - RKTableSection* section = [RKTableSection sectionForObjects:objects withMappings:mappings]; +- (void)testReplaceTheObjectAtAGivenIndex +{ + NSArray *objects = [NSArray arrayWithObjects:@"first object", @"second object", nil]; + RKTableViewCellMappings *mappings = [RKTableViewCellMappings new]; + RKTableSection *section = [RKTableSection sectionForObjects:objects withMappings:mappings]; assertThat([section objectAtIndex:0], is(equalTo(@"first object"))); assertThat([section objectAtIndex:1], is(equalTo(@"second object"))); [section replaceObjectAtIndex:0 withObject:@"new first object"]; assertThat([section objectAtIndex:0], is(equalTo(@"new first object"))); } -- (void)testMoveTheObjectAtAGivenIndex { - NSArray* objects = [NSArray arrayWithObjects:@"first object", @"second object", nil]; - RKTableViewCellMappings* mappings = [RKTableViewCellMappings new]; - RKTableSection* section = [RKTableSection sectionForObjects:objects withMappings:mappings]; +- (void)testMoveTheObjectAtAGivenIndex +{ + NSArray *objects = [NSArray arrayWithObjects:@"first object", @"second object", nil]; + RKTableViewCellMappings *mappings = [RKTableViewCellMappings new]; + RKTableSection *section = [RKTableSection sectionForObjects:objects withMappings:mappings]; assertThat([section objectAtIndex:0], is(equalTo(@"first object"))); assertThat([section objectAtIndex:1], is(equalTo(@"second object"))); [section moveObjectAtIndex:1 toIndex:0]; diff --git a/Tests/Logic/CoreData/NSManagedObject+ActiveRecordTest.m b/Tests/Logic/CoreData/NSManagedObject+ActiveRecordTest.m index 7c5c1a4c5b..eed93942d2 100644 --- a/Tests/Logic/CoreData/NSManagedObject+ActiveRecordTest.m +++ b/Tests/Logic/CoreData/NSManagedObject+ActiveRecordTest.m @@ -53,11 +53,11 @@ - (void)testFindByPrimaryKeyWithStringValueForNumericProperty RKManagedObjectStore *store = [RKTestFactory managedObjectStore]; NSEntityDescription *entity = [RKHuman entityDescription]; entity.primaryKeyAttributeName = @"railsID"; - + RKHuman *human = [RKHuman createEntity]; human.railsID = [NSNumber numberWithInt:12345]; [store save:nil]; - + RKHuman *foundHuman = [RKHuman findByPrimaryKey:@"12345" inContext:store.primaryManagedObjectContext]; assertThat(foundHuman, is(equalTo(human))); } diff --git a/Tests/Logic/CoreData/RKEntityByAttributeCacheTest.m b/Tests/Logic/CoreData/RKEntityByAttributeCacheTest.m index b50efc2cb9..7bd7753f2a 100644 --- a/Tests/Logic/CoreData/RKEntityByAttributeCacheTest.m +++ b/Tests/Logic/CoreData/RKEntityByAttributeCacheTest.m @@ -353,7 +353,8 @@ - (void)testCacheIsFlushedOnMemoryWarning } #endif -- (void)testCreatingProcessingAndDeletingObjectsWorksAsExpected { +- (void)testCreatingProcessingAndDeletingObjectsWorksAsExpected +{ self.cache.monitorsContextForChanges = YES; RKHuman *human1 = [RKHuman createInContext:self.objectStore.primaryManagedObjectContext]; diff --git a/Tests/Logic/CoreData/RKManagedObjectLoaderTest.m b/Tests/Logic/CoreData/RKManagedObjectLoaderTest.m index efd461f15f..bbbd5e94e0 100644 --- a/Tests/Logic/CoreData/RKManagedObjectLoaderTest.m +++ b/Tests/Logic/CoreData/RKManagedObjectLoaderTest.m @@ -34,22 +34,23 @@ @interface RKManagedObjectLoaderTest : RKTestCase { @implementation RKManagedObjectLoaderTest -- (void)testShouldDeleteObjectFromLocalStoreOnDELETE { - RKManagedObjectStore* store = [RKTestFactory managedObjectStore]; +- (void)testShouldDeleteObjectFromLocalStoreOnDELETE +{ + RKManagedObjectStore *store = [RKTestFactory managedObjectStore]; [store save:nil]; - RKObjectManager* objectManager = [RKTestFactory objectManager]; + RKObjectManager *objectManager = [RKTestFactory objectManager]; objectManager.objectStore = store; - RKHuman* human = [RKHuman object]; + RKHuman *human = [RKHuman object]; human.name = @"Blake Watters"; human.railsID = [NSNumber numberWithInt:1]; [objectManager.objectStore save:nil]; assertThat(objectManager.objectStore.primaryManagedObjectContext, is(equalTo(store.primaryManagedObjectContext))); - RKManagedObjectMapping* mapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:store]; - RKTestResponseLoader* responseLoader = [RKTestResponseLoader responseLoader]; + RKManagedObjectMapping *mapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:store]; + RKTestResponseLoader *responseLoader = [RKTestResponseLoader responseLoader]; RKURL *URL = [objectManager.baseURL URLByAppendingResourcePath:@"/humans/1"]; - RKManagedObjectLoader* objectLoader = [RKManagedObjectLoader loaderWithURL:URL mappingProvider:objectManager.mappingProvider objectStore:store]; + RKManagedObjectLoader *objectLoader = [RKManagedObjectLoader loaderWithURL:URL mappingProvider:objectManager.mappingProvider objectStore:store]; objectLoader.delegate = responseLoader; objectLoader.method = RKRequestMethodDELETE; objectLoader.objectMapping = mapping; @@ -59,32 +60,34 @@ - (void)testShouldDeleteObjectFromLocalStoreOnDELETE { assertThatBool([human isDeleted], equalToBool(YES)); } -- (void)testShouldLoadAnObjectWithAToOneRelationship { - RKManagedObjectStore* store = [RKTestFactory managedObjectStore]; - RKObjectManager* objectManager = [RKTestFactory objectManager]; +- (void)testShouldLoadAnObjectWithAToOneRelationship +{ + RKManagedObjectStore *store = [RKTestFactory managedObjectStore]; + RKObjectManager *objectManager = [RKTestFactory objectManager]; objectManager.objectStore = store; - RKObjectMapping* humanMapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:store]; + RKObjectMapping *humanMapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:store]; [humanMapping mapAttributes:@"name", nil]; - RKObjectMapping* catMapping = [RKManagedObjectMapping mappingForClass:[RKCat class] inManagedObjectStore:store]; + RKObjectMapping *catMapping = [RKManagedObjectMapping mappingForClass:[RKCat class] inManagedObjectStore:store]; [catMapping mapAttributes:@"name", nil]; [humanMapping mapKeyPath:@"favorite_cat" toRelationship:@"favoriteCat" withMapping:catMapping]; [objectManager.mappingProvider setMapping:humanMapping forKeyPath:@"human"]; - RKTestResponseLoader* responseLoader = [RKTestResponseLoader responseLoader]; + RKTestResponseLoader *responseLoader = [RKTestResponseLoader responseLoader]; RKURL *URL = [objectManager.baseURL URLByAppendingResourcePath:@"/JSON/humans/with_to_one_relationship.json"]; - RKManagedObjectLoader* objectLoader = [RKManagedObjectLoader loaderWithURL:URL mappingProvider:objectManager.mappingProvider objectStore:store]; + RKManagedObjectLoader *objectLoader = [RKManagedObjectLoader loaderWithURL:URL mappingProvider:objectManager.mappingProvider objectStore:store]; objectLoader.delegate = responseLoader; [objectLoader send]; [responseLoader waitForResponse]; - RKHuman* human = [responseLoader.objects lastObject]; + RKHuman *human = [responseLoader.objects lastObject]; assertThat(human, isNot(nilValue())); assertThat(human.favoriteCat, isNot(nilValue())); assertThat(human.favoriteCat.name, is(equalTo(@"Asia"))); } -- (void)testShouldDeleteObjectsMissingFromPayloadReturnedByObjectCache { - RKManagedObjectStore* store = [RKTestFactory managedObjectStore]; - RKManagedObjectMapping* humanMapping = [RKManagedObjectMapping mappingForEntityWithName:@"RKHuman" +- (void)testShouldDeleteObjectsMissingFromPayloadReturnedByObjectCache +{ + RKManagedObjectStore *store = [RKTestFactory managedObjectStore]; + RKManagedObjectMapping *humanMapping = [RKManagedObjectMapping mappingForEntityWithName:@"RKHuman" inManagedObjectStore:store]; [humanMapping mapKeyPath:@"id" toAttribute:@"railsID"]; [humanMapping mapAttributes:@"name", nil]; @@ -94,16 +97,16 @@ - (void)testShouldDeleteObjectsMissingFromPayloadReturnedByObjectCache { // Create 3 objects, we will expect 2 after the load [RKHuman truncateAll]; assertThatUnsignedInteger([RKHuman count:nil], is(equalToInt(0))); - RKHuman* blake = [RKHuman createEntity]; + RKHuman *blake = [RKHuman createEntity]; blake.railsID = [NSNumber numberWithInt:123]; - RKHuman* other = [RKHuman createEntity]; + RKHuman *other = [RKHuman createEntity]; other.railsID = [NSNumber numberWithInt:456]; - RKHuman* deleteMe = [RKHuman createEntity]; + RKHuman *deleteMe = [RKHuman createEntity]; deleteMe.railsID = [NSNumber numberWithInt:9999]; [store save:nil]; assertThatUnsignedInteger([RKHuman count:nil], is(equalToInt(3))); - RKObjectManager* objectManager = [RKTestFactory objectManager]; + RKObjectManager *objectManager = [RKTestFactory objectManager]; [objectManager.mappingProvider setObjectMapping:humanMapping forResourcePathPattern:@"/JSON/humans/all.json" withFetchRequestBlock:^ (NSString *resourcePath) { @@ -111,7 +114,7 @@ - (void)testShouldDeleteObjectsMissingFromPayloadReturnedByObjectCache { }]; objectManager.objectStore = store; - RKTestResponseLoader* responseLoader = [RKTestResponseLoader responseLoader]; + RKTestResponseLoader *responseLoader = [RKTestResponseLoader responseLoader]; responseLoader.timeout = 25; RKURL *URL = [objectManager.baseURL URLByAppendingResourcePath:@"/JSON/humans/all.json"]; RKManagedObjectLoader *objectLoader = [RKManagedObjectLoader loaderWithURL:URL mappingProvider:objectManager.mappingProvider objectStore:store]; @@ -125,22 +128,24 @@ - (void)testShouldDeleteObjectsMissingFromPayloadReturnedByObjectCache { assertThatBool([deleteMe isDeleted], is(equalToBool(YES))); } -- (void)testShouldNotAssertDuringObjectMappingOnSynchronousRequest { - RKManagedObjectStore* store = [RKTestFactory managedObjectStore]; - RKObjectManager* objectManager = [RKTestFactory objectManager]; +- (void)testShouldNotAssertDuringObjectMappingOnSynchronousRequest +{ + RKManagedObjectStore *store = [RKTestFactory managedObjectStore]; + RKObjectManager *objectManager = [RKTestFactory objectManager]; objectManager.objectStore = store; - RKObjectMapping* mapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:store]; - RKManagedObjectLoader* objectLoader = [objectManager loaderWithResourcePath:@"/humans/1"]; + RKObjectMapping *mapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:store]; + RKManagedObjectLoader *objectLoader = [objectManager loaderWithResourcePath:@"/humans/1"]; objectLoader.objectMapping = mapping; RKResponse *response = [objectLoader sendSynchronously]; - NSArray* humans = [RKHuman findAll]; + NSArray *humans = [RKHuman findAll]; assertThatUnsignedInteger([humans count], is(equalToInt(1))); assertThatInteger(response.statusCode, is(equalToInt(200))); } -- (void)testShouldSkipObjectMappingOnRequestCacheHitWhenObjectCachePresent { +- (void)testShouldSkipObjectMappingOnRequestCacheHitWhenObjectCachePresent +{ [RKTestFactory clearCacheDirectory]; RKObjectManager *objectManager = [RKTestFactory objectManager]; @@ -200,7 +205,8 @@ - (void)testShouldSkipObjectMappingOnRequestCacheHitWhenObjectCachePresent { } } -- (void)testTheOnDidFailBlockIsInvokedOnFailure { +- (void)testTheOnDidFailBlockIsInvokedOnFailure +{ RKObjectManager *objectManager = [RKTestFactory objectManager]; RKManagedObjectLoader *loader = [objectManager loaderWithResourcePath:@"/fail"]; RKTestResponseLoader *responseLoader = [RKTestResponseLoader responseLoader]; @@ -214,16 +220,17 @@ - (void)testTheOnDidFailBlockIsInvokedOnFailure { assertThatBool(invoked, is(equalToBool(YES))); } -- (void)testThatObjectLoadedDidFinishLoadingIsCalledOnStoreSaveFailure { - RKManagedObjectStore* store = [RKTestFactory managedObjectStore]; - RKObjectManager* objectManager = [RKTestFactory objectManager]; +- (void)testThatObjectLoadedDidFinishLoadingIsCalledOnStoreSaveFailure +{ + RKManagedObjectStore *store = [RKTestFactory managedObjectStore]; + RKObjectManager *objectManager = [RKTestFactory objectManager]; objectManager.objectStore = store; id mockStore = [OCMockObject partialMockForObject:store]; BOOL success = NO; [[[mockStore stub] andReturnValue:OCMOCK_VALUE(success)] save:[OCMArg anyPointer]]; - RKObjectMapping* mapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:store]; - RKManagedObjectLoader* objectLoader = [objectManager loaderWithResourcePath:@"/humans/1"]; + RKObjectMapping *mapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:store]; + RKManagedObjectLoader *objectLoader = [objectManager loaderWithResourcePath:@"/humans/1"]; objectLoader.objectMapping = mapping; RKTestResponseLoader *responseLoader = [RKTestResponseLoader responseLoader]; diff --git a/Tests/Logic/CoreData/RKManagedObjectMappingOperationTest.m b/Tests/Logic/CoreData/RKManagedObjectMappingOperationTest.m index 7eaded59f0..a739831575 100644 --- a/Tests/Logic/CoreData/RKManagedObjectMappingOperationTest.m +++ b/Tests/Logic/CoreData/RKManagedObjectMappingOperationTest.m @@ -35,300 +35,313 @@ @interface RKManagedObjectMappingOperationTest : RKTestCase { @implementation RKManagedObjectMappingOperationTest -- (void)testShouldOverloadInitializationOfRKObjectMappingOperationToReturnInstancesOfRKManagedObjectMappingOperationWhenAppropriate { +- (void)testShouldOverloadInitializationOfRKObjectMappingOperationToReturnInstancesOfRKManagedObjectMappingOperationWhenAppropriate +{ RKManagedObjectStore *store = [RKTestFactory managedObjectStore]; - RKManagedObjectMapping* managedMapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:store]; - NSDictionary* sourceObject = [NSDictionary dictionary]; - RKHuman* human = [RKHuman createEntity]; - RKObjectMappingOperation* operation = [RKObjectMappingOperation mappingOperationFromObject:sourceObject toObject:human withMapping:managedMapping]; + RKManagedObjectMapping *managedMapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:store]; + NSDictionary *sourceObject = [NSDictionary dictionary]; + RKHuman *human = [RKHuman createEntity]; + RKObjectMappingOperation *operation = [RKObjectMappingOperation mappingOperationFromObject:sourceObject toObject:human withMapping:managedMapping]; assertThat(operation, is(instanceOf([RKManagedObjectMappingOperation class]))); } -- (void)testShouldOverloadInitializationOfRKObjectMappingOperationButReturnUnmanagedMappingOperationWhenAppropriate { - RKObjectMapping* vanillaMapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; - NSDictionary* sourceObject = [NSDictionary dictionary]; - NSMutableDictionary* destinationObject = [NSMutableDictionary dictionary]; - RKObjectMappingOperation* operation = [RKObjectMappingOperation mappingOperationFromObject:sourceObject toObject:destinationObject withMapping:vanillaMapping]; +- (void)testShouldOverloadInitializationOfRKObjectMappingOperationButReturnUnmanagedMappingOperationWhenAppropriate +{ + RKObjectMapping *vanillaMapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; + NSDictionary *sourceObject = [NSDictionary dictionary]; + NSMutableDictionary *destinationObject = [NSMutableDictionary dictionary]; + RKObjectMappingOperation *operation = [RKObjectMappingOperation mappingOperationFromObject:sourceObject toObject:destinationObject withMapping:vanillaMapping]; assertThat(operation, is(instanceOf([RKObjectMappingOperation class]))); } -- (void)testShouldConnectRelationshipsByPrimaryKey { - RKManagedObjectStore* objectStore = [RKTestFactory managedObjectStore]; +- (void)testShouldConnectRelationshipsByPrimaryKey +{ + RKManagedObjectStore *objectStore = [RKTestFactory managedObjectStore]; - RKManagedObjectMapping* catMapping = [RKManagedObjectMapping mappingForClass:[RKCat class] inManagedObjectStore:objectStore]; + RKManagedObjectMapping *catMapping = [RKManagedObjectMapping mappingForClass:[RKCat class] inManagedObjectStore:objectStore]; catMapping.primaryKeyAttribute = @"railsID"; [catMapping mapAttributes:@"name", nil]; - RKManagedObjectMapping* humanMapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:objectStore]; + RKManagedObjectMapping *humanMapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:objectStore]; humanMapping.primaryKeyAttribute = @"railsID"; [humanMapping mapAttributes:@"name", @"favoriteCatID", nil]; [humanMapping hasOne:@"favoriteCat" withMapping:catMapping]; [humanMapping connectRelationship:@"favoriteCat" withObjectForPrimaryKeyAttribute:@"favoriteCatID"]; // Create a cat to connect - RKCat* cat = [RKCat object]; + RKCat *cat = [RKCat object]; cat.name = @"Asia"; cat.railsID = [NSNumber numberWithInt:31337]; [objectStore save:nil]; - NSDictionary* mappableData = [NSDictionary dictionaryWithKeysAndObjects:@"name", @"Blake", @"favoriteCatID", [NSNumber numberWithInt:31337], nil]; - RKHuman* human = [RKHuman object]; - RKManagedObjectMappingOperation* operation = [[RKManagedObjectMappingOperation alloc] initWithSourceObject:mappableData destinationObject:human mapping:humanMapping]; - NSError* error = nil; + NSDictionary *mappableData = [NSDictionary dictionaryWithKeysAndObjects:@"name", @"Blake", @"favoriteCatID", [NSNumber numberWithInt:31337], nil]; + RKHuman *human = [RKHuman object]; + RKManagedObjectMappingOperation *operation = [[RKManagedObjectMappingOperation alloc] initWithSourceObject:mappableData destinationObject:human mapping:humanMapping]; + NSError *error = nil; BOOL success = [operation performMapping:&error]; assertThatBool(success, is(equalToBool(YES))); assertThat(human.favoriteCat, isNot(nilValue())); assertThat(human.favoriteCat.name, is(equalTo(@"Asia"))); } -- (void)testConnectRelationshipsDoesNotLeakMemory { - RKManagedObjectStore* objectStore = [RKTestFactory managedObjectStore]; +- (void)testConnectRelationshipsDoesNotLeakMemory +{ + RKManagedObjectStore *objectStore = [RKTestFactory managedObjectStore]; - RKManagedObjectMapping* catMapping = [RKManagedObjectMapping mappingForClass:[RKCat class] inManagedObjectStore:objectStore]; + RKManagedObjectMapping *catMapping = [RKManagedObjectMapping mappingForClass:[RKCat class] inManagedObjectStore:objectStore]; catMapping.primaryKeyAttribute = @"railsID"; [catMapping mapAttributes:@"name", nil]; - RKManagedObjectMapping* humanMapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:objectStore]; + RKManagedObjectMapping *humanMapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:objectStore]; humanMapping.primaryKeyAttribute = @"railsID"; [humanMapping mapAttributes:@"name", @"favoriteCatID", nil]; [humanMapping hasOne:@"favoriteCat" withMapping:catMapping]; [humanMapping connectRelationship:@"favoriteCat" withObjectForPrimaryKeyAttribute:@"favoriteCatID"]; // Create a cat to connect - RKCat* cat = [RKCat object]; + RKCat *cat = [RKCat object]; cat.name = @"Asia"; cat.railsID = [NSNumber numberWithInt:31337]; [objectStore save:nil]; - NSDictionary* mappableData = [NSDictionary dictionaryWithKeysAndObjects:@"name", @"Blake", @"favoriteCatID", [NSNumber numberWithInt:31337], nil]; - RKHuman* human = [RKHuman object]; - RKManagedObjectMappingOperation* operation = [[RKManagedObjectMappingOperation alloc] initWithSourceObject:mappableData destinationObject:human mapping:humanMapping]; + NSDictionary *mappableData = [NSDictionary dictionaryWithKeysAndObjects:@"name", @"Blake", @"favoriteCatID", [NSNumber numberWithInt:31337], nil]; + RKHuman *human = [RKHuman object]; + RKManagedObjectMappingOperation *operation = [[RKManagedObjectMappingOperation alloc] initWithSourceObject:mappableData destinationObject:human mapping:humanMapping]; operation.queue = [RKMappingOperationQueue new]; - NSError* error = nil; + NSError *error = nil; [operation performMapping:&error]; assertThatInteger([operation retainCount], is(equalToInteger(1))); } -- (void)testConnectionOfHasManyRelationshipsByPrimaryKey { - RKManagedObjectStore* objectStore = [RKTestFactory managedObjectStore]; +- (void)testConnectionOfHasManyRelationshipsByPrimaryKey +{ + RKManagedObjectStore *objectStore = [RKTestFactory managedObjectStore]; - RKManagedObjectMapping* catMapping = [RKManagedObjectMapping mappingForClass:[RKCat class] inManagedObjectStore:objectStore]; + RKManagedObjectMapping *catMapping = [RKManagedObjectMapping mappingForClass:[RKCat class] inManagedObjectStore:objectStore]; catMapping.primaryKeyAttribute = @"railsID"; [catMapping mapAttributes:@"name", nil]; - RKManagedObjectMapping* humanMapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:objectStore]; + RKManagedObjectMapping *humanMapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:objectStore]; humanMapping.primaryKeyAttribute = @"railsID"; [humanMapping mapAttributes:@"name", @"favoriteCatID", nil]; [humanMapping hasOne:@"favoriteCat" withMapping:catMapping]; [humanMapping connectRelationship:@"favoriteCat" withObjectForPrimaryKeyAttribute:@"favoriteCatID"]; // Create a cat to connect - RKCat* cat = [RKCat object]; + RKCat *cat = [RKCat object]; cat.name = @"Asia"; cat.railsID = [NSNumber numberWithInt:31337]; [objectStore save:nil]; - NSDictionary* mappableData = [NSDictionary dictionaryWithKeysAndObjects:@"name", @"Blake", @"favoriteCatID", [NSNumber numberWithInt:31337], nil]; - RKHuman* human = [RKHuman object]; - RKManagedObjectMappingOperation* operation = [[RKManagedObjectMappingOperation alloc] initWithSourceObject:mappableData destinationObject:human mapping:humanMapping]; - NSError* error = nil; + NSDictionary *mappableData = [NSDictionary dictionaryWithKeysAndObjects:@"name", @"Blake", @"favoriteCatID", [NSNumber numberWithInt:31337], nil]; + RKHuman *human = [RKHuman object]; + RKManagedObjectMappingOperation *operation = [[RKManagedObjectMappingOperation alloc] initWithSourceObject:mappableData destinationObject:human mapping:humanMapping]; + NSError *error = nil; BOOL success = [operation performMapping:&error]; assertThatBool(success, is(equalToBool(YES))); assertThat(human.favoriteCat, isNot(nilValue())); assertThat(human.favoriteCat.name, is(equalTo(@"Asia"))); } -- (void)testShouldConnectRelationshipsByPrimaryKeyWithDifferentSourceAndDestinationKeyPaths { - RKManagedObjectStore* objectStore = [RKTestFactory managedObjectStore]; +- (void)testShouldConnectRelationshipsByPrimaryKeyWithDifferentSourceAndDestinationKeyPaths +{ + RKManagedObjectStore *objectStore = [RKTestFactory managedObjectStore]; - RKManagedObjectMapping* catMapping = [RKManagedObjectMapping mappingForClass:[RKCat class] inManagedObjectStore:objectStore]; + RKManagedObjectMapping *catMapping = [RKManagedObjectMapping mappingForClass:[RKCat class] inManagedObjectStore:objectStore]; catMapping.primaryKeyAttribute = @"railsID"; [catMapping mapAttributes:@"name", nil]; - RKManagedObjectMapping* humanMapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:objectStore]; + RKManagedObjectMapping *humanMapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:objectStore]; humanMapping.primaryKeyAttribute = @"railsID"; [humanMapping mapAttributes:@"name", @"favoriteCatID", @"catIDs", nil]; [humanMapping mapRelationship:@"cats" withMapping:catMapping]; [humanMapping connectRelationship:@"cats" withObjectForPrimaryKeyAttribute:@"catIDs"]; // Create a couple of cats to connect - RKCat* asia = [RKCat object]; + RKCat *asia = [RKCat object]; asia.name = @"Asia"; asia.railsID = [NSNumber numberWithInt:31337]; - RKCat* roy = [RKCat object]; + RKCat *roy = [RKCat object]; roy.name = @"Reginald Royford Williams III"; roy.railsID = [NSNumber numberWithInt:31338]; [objectStore save:nil]; NSArray *catIDs = [NSArray arrayWithObjects:[NSNumber numberWithInt:31337], [NSNumber numberWithInt:31338], nil]; - NSDictionary* mappableData = [NSDictionary dictionaryWithKeysAndObjects:@"name", @"Blake", @"catIDs", catIDs, nil]; - RKHuman* human = [RKHuman object]; + NSDictionary *mappableData = [NSDictionary dictionaryWithKeysAndObjects:@"name", @"Blake", @"catIDs", catIDs, nil]; + RKHuman *human = [RKHuman object]; - RKManagedObjectMappingOperation* operation = [[RKManagedObjectMappingOperation alloc] initWithSourceObject:mappableData destinationObject:human mapping:humanMapping]; - NSError* error = nil; + RKManagedObjectMappingOperation *operation = [[RKManagedObjectMappingOperation alloc] initWithSourceObject:mappableData destinationObject:human mapping:humanMapping]; + NSError *error = nil; BOOL success = [operation performMapping:&error]; assertThatBool(success, is(equalToBool(YES))); assertThat(human.cats, isNot(nilValue())); assertThat([human.cats valueForKeyPath:@"name"], containsInAnyOrder(@"Asia", @"Reginald Royford Williams III", nil)); } -- (void)testShouldLoadNestedHasManyRelationship { - RKManagedObjectStore* objectStore = [RKTestFactory managedObjectStore]; - RKManagedObjectMapping* catMapping = [RKManagedObjectMapping mappingForClass:[RKCat class] inManagedObjectStore:objectStore]; +- (void)testShouldLoadNestedHasManyRelationship +{ + RKManagedObjectStore *objectStore = [RKTestFactory managedObjectStore]; + RKManagedObjectMapping *catMapping = [RKManagedObjectMapping mappingForClass:[RKCat class] inManagedObjectStore:objectStore]; catMapping.primaryKeyAttribute = @"railsID"; [catMapping mapAttributes:@"name", nil]; - RKManagedObjectMapping* humanMapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:objectStore]; + RKManagedObjectMapping *humanMapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:objectStore]; humanMapping.primaryKeyAttribute = @"railsID"; [humanMapping mapAttributes:@"name", @"favoriteCatID", nil]; [humanMapping hasMany:@"cats" withMapping:catMapping]; - NSArray* catsData = [NSArray arrayWithObject:[NSDictionary dictionaryWithObject:@"Asia" forKey:@"name"]]; - NSDictionary* mappableData = [NSDictionary dictionaryWithKeysAndObjects:@"name", @"Blake", @"favoriteCatID", [NSNumber numberWithInt:31337], @"cats", catsData, nil]; - RKHuman* human = [RKHuman object]; - RKManagedObjectMappingOperation* operation = [[RKManagedObjectMappingOperation alloc] initWithSourceObject:mappableData destinationObject:human mapping:humanMapping]; - NSError* error = nil; + NSArray *catsData = [NSArray arrayWithObject:[NSDictionary dictionaryWithObject:@"Asia" forKey:@"name"]]; + NSDictionary *mappableData = [NSDictionary dictionaryWithKeysAndObjects:@"name", @"Blake", @"favoriteCatID", [NSNumber numberWithInt:31337], @"cats", catsData, nil]; + RKHuman *human = [RKHuman object]; + RKManagedObjectMappingOperation *operation = [[RKManagedObjectMappingOperation alloc] initWithSourceObject:mappableData destinationObject:human mapping:humanMapping]; + NSError *error = nil; BOOL success = [operation performMapping:&error]; assertThatBool(success, is(equalToBool(YES))); } -- (void)testShouldLoadOrderedHasManyRelationship { - RKManagedObjectStore* objectStore = [RKTestFactory managedObjectStore]; - RKManagedObjectMapping* catMapping = [RKManagedObjectMapping mappingForClass:[RKCat class] inManagedObjectStore:objectStore]; +- (void)testShouldLoadOrderedHasManyRelationship +{ + RKManagedObjectStore *objectStore = [RKTestFactory managedObjectStore]; + RKManagedObjectMapping *catMapping = [RKManagedObjectMapping mappingForClass:[RKCat class] inManagedObjectStore:objectStore]; catMapping.primaryKeyAttribute = @"railsID"; [catMapping mapAttributes:@"name", nil]; - RKManagedObjectMapping* humanMapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:objectStore]; + RKManagedObjectMapping *humanMapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:objectStore]; humanMapping.primaryKeyAttribute = @"railsID"; [humanMapping mapAttributes:@"name", @"favoriteCatID", nil]; [humanMapping mapKeyPath:@"cats" toRelationship:@"catsInOrderByAge" withMapping:catMapping]; - NSArray* catsData = [NSArray arrayWithObject:[NSDictionary dictionaryWithObject:@"Asia" forKey:@"name"]]; - NSDictionary* mappableData = [NSDictionary dictionaryWithKeysAndObjects:@"name", @"Blake", @"favoriteCatID", [NSNumber numberWithInt:31337], @"cats", catsData, nil]; - RKHuman* human = [RKHuman object]; - RKManagedObjectMappingOperation* operation = [[RKManagedObjectMappingOperation alloc] initWithSourceObject:mappableData destinationObject:human mapping:humanMapping]; - NSError* error = nil; + NSArray *catsData = [NSArray arrayWithObject:[NSDictionary dictionaryWithObject:@"Asia" forKey:@"name"]]; + NSDictionary *mappableData = [NSDictionary dictionaryWithKeysAndObjects:@"name", @"Blake", @"favoriteCatID", [NSNumber numberWithInt:31337], @"cats", catsData, nil]; + RKHuman *human = [RKHuman object]; + RKManagedObjectMappingOperation *operation = [[RKManagedObjectMappingOperation alloc] initWithSourceObject:mappableData destinationObject:human mapping:humanMapping]; + NSError *error = nil; BOOL success = [operation performMapping:&error]; assertThatBool(success, is(equalToBool(YES))); assertThat([human catsInOrderByAge], isNot(empty())); } -- (void)testShouldMapNullToAHasManyRelationship { +- (void)testShouldMapNullToAHasManyRelationship +{ RKManagedObjectStore *objectStore = [RKTestFactory managedObjectStore]; - RKManagedObjectMapping* catMapping = [RKManagedObjectMapping mappingForClass:[RKCat class] inManagedObjectStore:objectStore]; + RKManagedObjectMapping *catMapping = [RKManagedObjectMapping mappingForClass:[RKCat class] inManagedObjectStore:objectStore]; [catMapping mapAttributes:@"name", nil]; - RKManagedObjectMapping* humanMapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:objectStore]; + RKManagedObjectMapping *humanMapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:objectStore]; [humanMapping mapAttributes:@"name", @"favoriteCatID", nil]; [humanMapping hasMany:@"cats" withMapping:catMapping]; - NSDictionary* mappableData = [NSDictionary dictionaryWithKeysAndObjects:@"name", @"Blake", @"cats", [NSNull null], nil]; - RKHuman* human = [RKHuman object]; - RKManagedObjectMappingOperation* operation = [[RKManagedObjectMappingOperation alloc] initWithSourceObject:mappableData destinationObject:human mapping:humanMapping]; - NSError* error = nil; + NSDictionary *mappableData = [NSDictionary dictionaryWithKeysAndObjects:@"name", @"Blake", @"cats", [NSNull null], nil]; + RKHuman *human = [RKHuman object]; + RKManagedObjectMappingOperation *operation = [[RKManagedObjectMappingOperation alloc] initWithSourceObject:mappableData destinationObject:human mapping:humanMapping]; + NSError *error = nil; BOOL success = [operation performMapping:&error]; assertThatBool(success, is(equalToBool(YES))); assertThat(human.cats, is(empty())); } -- (void)testShouldLoadNestedHasManyRelationshipWithoutABackingClass { - RKManagedObjectStore* objectStore = [RKTestFactory managedObjectStore]; - RKManagedObjectMapping* cloudMapping = [RKManagedObjectMapping mappingForEntityWithName:@"RKCloud" inManagedObjectStore:objectStore]; +- (void)testShouldLoadNestedHasManyRelationshipWithoutABackingClass +{ + RKManagedObjectStore *objectStore = [RKTestFactory managedObjectStore]; + RKManagedObjectMapping *cloudMapping = [RKManagedObjectMapping mappingForEntityWithName:@"RKCloud" inManagedObjectStore:objectStore]; [cloudMapping mapAttributes:@"name", nil]; - RKManagedObjectMapping* stormMapping = [RKManagedObjectMapping mappingForEntityWithName:@"RKStorm" inManagedObjectStore:objectStore]; + RKManagedObjectMapping *stormMapping = [RKManagedObjectMapping mappingForEntityWithName:@"RKStorm" inManagedObjectStore:objectStore]; [stormMapping mapAttributes:@"name", @"favoriteCatID", nil]; [stormMapping hasMany:@"clouds" withMapping:cloudMapping]; - NSArray* cloudsData = [NSArray arrayWithObject:[NSDictionary dictionaryWithObject:@"Nimbus" forKey:@"name"]]; - NSDictionary* mappableData = [NSDictionary dictionaryWithKeysAndObjects:@"name", @"Hurricane", @"clouds", cloudsData, nil]; - NSEntityDescription* entity = [NSEntityDescription entityForName:@"RKStorm" inManagedObjectContext:objectStore.primaryManagedObjectContext]; - NSManagedObject* storm = [[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:objectStore.primaryManagedObjectContext]; - RKManagedObjectMappingOperation* operation = [[RKManagedObjectMappingOperation alloc] initWithSourceObject:mappableData destinationObject:storm mapping:stormMapping]; - NSError* error = nil; + NSArray *cloudsData = [NSArray arrayWithObject:[NSDictionary dictionaryWithObject:@"Nimbus" forKey:@"name"]]; + NSDictionary *mappableData = [NSDictionary dictionaryWithKeysAndObjects:@"name", @"Hurricane", @"clouds", cloudsData, nil]; + NSEntityDescription *entity = [NSEntityDescription entityForName:@"RKStorm" inManagedObjectContext:objectStore.primaryManagedObjectContext]; + NSManagedObject *storm = [[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:objectStore.primaryManagedObjectContext]; + RKManagedObjectMappingOperation *operation = [[RKManagedObjectMappingOperation alloc] initWithSourceObject:mappableData destinationObject:storm mapping:stormMapping]; + NSError *error = nil; BOOL success = [operation performMapping:&error]; assertThatBool(success, is(equalToBool(YES))); } -- (void)testShouldDynamicallyConnectRelationshipsByPrimaryKeyWhenMatchingSucceeds { - RKManagedObjectStore* objectStore = [RKTestFactory managedObjectStore]; +- (void)testShouldDynamicallyConnectRelationshipsByPrimaryKeyWhenMatchingSucceeds +{ + RKManagedObjectStore *objectStore = [RKTestFactory managedObjectStore]; - RKManagedObjectMapping* catMapping = [RKManagedObjectMapping mappingForClass:[RKCat class] inManagedObjectStore:objectStore]; + RKManagedObjectMapping *catMapping = [RKManagedObjectMapping mappingForClass:[RKCat class] inManagedObjectStore:objectStore]; catMapping.primaryKeyAttribute = @"railsID"; [catMapping mapAttributes:@"name", nil]; - RKManagedObjectMapping* humanMapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:objectStore]; + RKManagedObjectMapping *humanMapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:objectStore]; humanMapping.primaryKeyAttribute = @"railsID"; [humanMapping mapAttributes:@"name", @"favoriteCatID", nil]; [humanMapping hasOne:@"favoriteCat" withMapping:catMapping]; [humanMapping connectRelationship:@"favoriteCat" withObjectForPrimaryKeyAttribute:@"favoriteCatID" whenValueOfKeyPath:@"name" isEqualTo:@"Blake"]; // Create a cat to connect - RKCat* cat = [RKCat object]; + RKCat *cat = [RKCat object]; cat.name = @"Asia"; cat.railsID = [NSNumber numberWithInt:31337]; [objectStore save:nil]; - NSDictionary* mappableData = [NSDictionary dictionaryWithKeysAndObjects:@"name", @"Blake", @"favoriteCatID", [NSNumber numberWithInt:31337], nil]; - RKHuman* human = [RKHuman object]; - RKManagedObjectMappingOperation* operation = [[RKManagedObjectMappingOperation alloc] initWithSourceObject:mappableData destinationObject:human mapping:humanMapping]; - NSError* error = nil; + NSDictionary *mappableData = [NSDictionary dictionaryWithKeysAndObjects:@"name", @"Blake", @"favoriteCatID", [NSNumber numberWithInt:31337], nil]; + RKHuman *human = [RKHuman object]; + RKManagedObjectMappingOperation *operation = [[RKManagedObjectMappingOperation alloc] initWithSourceObject:mappableData destinationObject:human mapping:humanMapping]; + NSError *error = nil; BOOL success = [operation performMapping:&error]; assertThatBool(success, is(equalToBool(YES))); assertThat(human.favoriteCat, isNot(nilValue())); assertThat(human.favoriteCat.name, is(equalTo(@"Asia"))); } -- (void)testShouldNotDynamicallyConnectRelationshipsByPrimaryKeyWhenMatchingFails { - RKManagedObjectStore* objectStore = [RKTestFactory managedObjectStore]; +- (void)testShouldNotDynamicallyConnectRelationshipsByPrimaryKeyWhenMatchingFails +{ + RKManagedObjectStore *objectStore = [RKTestFactory managedObjectStore]; - RKManagedObjectMapping* catMapping = [RKManagedObjectMapping mappingForClass:[RKCat class] inManagedObjectStore:objectStore]; + RKManagedObjectMapping *catMapping = [RKManagedObjectMapping mappingForClass:[RKCat class] inManagedObjectStore:objectStore]; catMapping.primaryKeyAttribute = @"railsID"; [catMapping mapAttributes:@"name", nil]; - RKManagedObjectMapping* humanMapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:objectStore]; + RKManagedObjectMapping *humanMapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:objectStore]; humanMapping.primaryKeyAttribute = @"railsID"; [humanMapping mapAttributes:@"name", @"favoriteCatID", nil]; [humanMapping hasOne:@"favoriteCat" withMapping:catMapping]; [humanMapping connectRelationship:@"favoriteCat" withObjectForPrimaryKeyAttribute:@"favoriteCatID" whenValueOfKeyPath:@"name" isEqualTo:@"Jeff"]; // Create a cat to connect - RKCat* cat = [RKCat object]; + RKCat *cat = [RKCat object]; cat.name = @"Asia"; cat.railsID = [NSNumber numberWithInt:31337]; [objectStore save:nil]; - NSDictionary* mappableData = [NSDictionary dictionaryWithKeysAndObjects:@"name", @"Blake", @"favoriteCatID", [NSNumber numberWithInt:31337], nil]; - RKHuman* human = [RKHuman object]; - RKManagedObjectMappingOperation* operation = [[RKManagedObjectMappingOperation alloc] initWithSourceObject:mappableData destinationObject:human mapping:humanMapping]; - NSError* error = nil; + NSDictionary *mappableData = [NSDictionary dictionaryWithKeysAndObjects:@"name", @"Blake", @"favoriteCatID", [NSNumber numberWithInt:31337], nil]; + RKHuman *human = [RKHuman object]; + RKManagedObjectMappingOperation *operation = [[RKManagedObjectMappingOperation alloc] initWithSourceObject:mappableData destinationObject:human mapping:humanMapping]; + NSError *error = nil; BOOL success = [operation performMapping:&error]; assertThatBool(success, is(equalToBool(YES))); assertThat(human.favoriteCat, is(nilValue())); } -- (void)testShouldConnectManyToManyRelationships { +- (void)testShouldConnectManyToManyRelationships +{ RKManagedObjectStore *store = [RKTestFactory managedObjectStore]; - RKManagedObjectMapping* childMapping = [RKManagedObjectMapping mappingForClass:[RKChild class] inManagedObjectStore:store]; + RKManagedObjectMapping *childMapping = [RKManagedObjectMapping mappingForClass:[RKChild class] inManagedObjectStore:store]; childMapping.primaryKeyAttribute = @"railsID"; [childMapping mapAttributes:@"name", nil]; - RKManagedObjectMapping* parentMapping = [RKManagedObjectMapping mappingForClass:[RKParent class] inManagedObjectStore:store]; + RKManagedObjectMapping *parentMapping = [RKManagedObjectMapping mappingForClass:[RKParent class] inManagedObjectStore:store]; parentMapping.primaryKeyAttribute = @"railsID"; [parentMapping mapAttributes:@"name", @"age", nil]; [parentMapping hasMany:@"children" withMapping:childMapping]; - NSArray* childMappableData = [NSArray arrayWithObjects:[NSDictionary dictionaryWithKeysAndObjects:@"name", @"Maya", nil], + NSArray *childMappableData = [NSArray arrayWithObjects:[NSDictionary dictionaryWithKeysAndObjects:@"name", @"Maya", nil], [NSDictionary dictionaryWithKeysAndObjects:@"name", @"Brady", nil], nil]; - NSDictionary* parentMappableData = [NSDictionary dictionaryWithKeysAndObjects:@"name", @"Win", + NSDictionary *parentMappableData = [NSDictionary dictionaryWithKeysAndObjects:@"name", @"Win", @"age", [NSNumber numberWithInt:34], @"children", childMappableData, nil]; - RKParent* parent = [RKParent object]; - RKManagedObjectMappingOperation* operation = [[RKManagedObjectMappingOperation alloc] initWithSourceObject:parentMappableData destinationObject:parent mapping:parentMapping]; - NSError* error = nil; + RKParent *parent = [RKParent object]; + RKManagedObjectMappingOperation *operation = [[RKManagedObjectMappingOperation alloc] initWithSourceObject:parentMappableData destinationObject:parent mapping:parentMapping]; + NSError *error = nil; BOOL success = [operation performMapping:&error]; assertThatBool(success, is(equalToBool(YES))); assertThat(parent.children, isNot(nilValue())); @@ -338,13 +351,14 @@ - (void)testShouldConnectManyToManyRelationships { assertThatUnsignedInteger([[[parent.children anyObject] parents] count], is(equalToInt(1))); } -- (void)testShouldConnectRelationshipsByPrimaryKeyRegardlessOfOrder { +- (void)testShouldConnectRelationshipsByPrimaryKeyRegardlessOfOrder +{ RKManagedObjectStore *store = [RKTestFactory managedObjectStore]; - RKManagedObjectMapping* parentMapping = [RKManagedObjectMapping mappingForClass:[RKParent class] inManagedObjectStore:store]; + RKManagedObjectMapping *parentMapping = [RKManagedObjectMapping mappingForClass:[RKParent class] inManagedObjectStore:store]; [parentMapping mapAttributes:@"parentID", nil]; parentMapping.primaryKeyAttribute = @"parentID"; - RKManagedObjectMapping* childMapping = [RKManagedObjectMapping mappingForClass:[RKChild class] inManagedObjectStore:store]; + RKManagedObjectMapping *childMapping = [RKManagedObjectMapping mappingForClass:[RKChild class] inManagedObjectStore:store]; [childMapping mapAttributes:@"fatherID", nil]; [childMapping mapRelationship:@"father" withMapping:parentMapping]; [childMapping connectRelationship:@"father" withObjectForPrimaryKeyAttribute:@"fatherID"]; @@ -364,15 +378,16 @@ - (void)testShouldConnectRelationshipsByPrimaryKeyRegardlessOfOrder { assertThat(child.father, is(notNilValue())); } -- (void)testMappingAPayloadContainingRepeatedObjectsDoesNotYieldDuplicatesWithFetchRequestMappingCache { +- (void)testMappingAPayloadContainingRepeatedObjectsDoesNotYieldDuplicatesWithFetchRequestMappingCache +{ RKManagedObjectStore *store = [RKTestFactory managedObjectStore]; store.cacheStrategy = [RKFetchRequestManagedObjectCache new]; - RKManagedObjectMapping* childMapping = [RKManagedObjectMapping mappingForClass:[RKChild class] inManagedObjectStore:store]; + RKManagedObjectMapping *childMapping = [RKManagedObjectMapping mappingForClass:[RKChild class] inManagedObjectStore:store]; childMapping.primaryKeyAttribute = @"childID"; [childMapping mapAttributes:@"name", @"childID", nil]; - RKManagedObjectMapping* parentMapping = [RKManagedObjectMapping mappingForClass:[RKParent class] inManagedObjectStore:store]; + RKManagedObjectMapping *parentMapping = [RKManagedObjectMapping mappingForClass:[RKParent class] inManagedObjectStore:store]; [parentMapping mapAttributes:@"parentID", @"name", nil]; parentMapping.primaryKeyAttribute = @"parentID"; [parentMapping mapRelationship:@"children" withMapping:childMapping]; @@ -392,15 +407,16 @@ - (void)testMappingAPayloadContainingRepeatedObjectsDoesNotYieldDuplicatesWithFe assertThatInteger(childrenCount, is(equalToInteger(4))); } -- (void)testMappingAPayloadContainingRepeatedObjectsDoesNotYieldDuplicatesWithInMemoryMappingCache { +- (void)testMappingAPayloadContainingRepeatedObjectsDoesNotYieldDuplicatesWithInMemoryMappingCache +{ RKManagedObjectStore *store = [RKTestFactory managedObjectStore]; store.cacheStrategy = [RKInMemoryManagedObjectCache new]; - RKManagedObjectMapping* childMapping = [RKManagedObjectMapping mappingForClass:[RKChild class] inManagedObjectStore:store]; + RKManagedObjectMapping *childMapping = [RKManagedObjectMapping mappingForClass:[RKChild class] inManagedObjectStore:store]; childMapping.primaryKeyAttribute = @"childID"; [childMapping mapAttributes:@"name", @"childID", nil]; - RKManagedObjectMapping* parentMapping = [RKManagedObjectMapping mappingForClass:[RKParent class] inManagedObjectStore:store]; + RKManagedObjectMapping *parentMapping = [RKManagedObjectMapping mappingForClass:[RKParent class] inManagedObjectStore:store]; [parentMapping mapAttributes:@"parentID", @"name", nil]; parentMapping.primaryKeyAttribute = @"parentID"; [parentMapping mapRelationship:@"children" withMapping:childMapping]; @@ -420,15 +436,16 @@ - (void)testMappingAPayloadContainingRepeatedObjectsDoesNotYieldDuplicatesWithIn assertThatInteger(childrenCount, is(equalToInteger(4))); } -- (void)testMappingAPayloadContainingRepeatedObjectsPerformsAcceptablyWithFetchRequestMappingCache { +- (void)testMappingAPayloadContainingRepeatedObjectsPerformsAcceptablyWithFetchRequestMappingCache +{ RKManagedObjectStore *store = [RKTestFactory managedObjectStore]; store.cacheStrategy = [RKFetchRequestManagedObjectCache new]; - RKManagedObjectMapping* childMapping = [RKManagedObjectMapping mappingForClass:[RKChild class] inManagedObjectStore:store]; + RKManagedObjectMapping *childMapping = [RKManagedObjectMapping mappingForClass:[RKChild class] inManagedObjectStore:store]; childMapping.primaryKeyAttribute = @"childID"; [childMapping mapAttributes:@"name", @"childID", nil]; - RKManagedObjectMapping* parentMapping = [RKManagedObjectMapping mappingForClass:[RKParent class] inManagedObjectStore:store]; + RKManagedObjectMapping *parentMapping = [RKManagedObjectMapping mappingForClass:[RKParent class] inManagedObjectStore:store]; [parentMapping mapAttributes:@"parentID", @"name", nil]; parentMapping.primaryKeyAttribute = @"parentID"; [parentMapping mapRelationship:@"children" withMapping:childMapping]; @@ -445,7 +462,7 @@ - (void)testMappingAPayloadContainingRepeatedObjectsPerformsAcceptablyWithFetchR RKLogConfigureByName("RestKit/CoreData", RKLogLevelOff); [RKBenchmark report:@"Mapping with Fetch Request Cache" executionBlock:^{ - for (NSUInteger i=0; i<50; i++) { + for (NSUInteger i = 0; i < 50; i++) { [mapper performMapping]; } }]; @@ -455,15 +472,16 @@ - (void)testMappingAPayloadContainingRepeatedObjectsPerformsAcceptablyWithFetchR assertThatInteger(childrenCount, is(equalToInteger(51))); } -- (void)testMappingAPayloadContainingRepeatedObjectsPerformsAcceptablyWithInMemoryMappingCache { +- (void)testMappingAPayloadContainingRepeatedObjectsPerformsAcceptablyWithInMemoryMappingCache +{ RKManagedObjectStore *store = [RKTestFactory managedObjectStore]; store.cacheStrategy = [RKInMemoryManagedObjectCache new]; - RKManagedObjectMapping* childMapping = [RKManagedObjectMapping mappingForClass:[RKChild class] inManagedObjectStore:store]; + RKManagedObjectMapping *childMapping = [RKManagedObjectMapping mappingForClass:[RKChild class] inManagedObjectStore:store]; childMapping.primaryKeyAttribute = @"childID"; [childMapping mapAttributes:@"name", @"childID", nil]; - RKManagedObjectMapping* parentMapping = [RKManagedObjectMapping mappingForClass:[RKParent class] inManagedObjectStore:store]; + RKManagedObjectMapping *parentMapping = [RKManagedObjectMapping mappingForClass:[RKParent class] inManagedObjectStore:store]; [parentMapping mapAttributes:@"parentID", @"name", nil]; parentMapping.primaryKeyAttribute = @"parentID"; [parentMapping mapRelationship:@"children" withMapping:childMapping]; @@ -480,7 +498,7 @@ - (void)testMappingAPayloadContainingRepeatedObjectsPerformsAcceptablyWithInMemo RKLogConfigureByName("RestKit/CoreData", RKLogLevelOff); [RKBenchmark report:@"Mapping with In Memory Cache" executionBlock:^{ - for (NSUInteger i=0; i<50; i++) { + for (NSUInteger i = 0; i < 50; i++) { [mapper performMapping]; } }]; diff --git a/Tests/Logic/CoreData/RKManagedObjectMappingTest.m b/Tests/Logic/CoreData/RKManagedObjectMappingTest.m index 4e05176ba9..104f32554e 100644 --- a/Tests/Logic/CoreData/RKManagedObjectMappingTest.m +++ b/Tests/Logic/CoreData/RKManagedObjectMappingTest.m @@ -42,65 +42,72 @@ - (void)tearDown [RKTestFactory tearDown]; } -- (void)testShouldReturnTheDefaultValueForACoreDataAttribute { +- (void)testShouldReturnTheDefaultValueForACoreDataAttribute +{ // Load Core Data RKManagedObjectStore *store = [RKTestFactory managedObjectStore]; - RKManagedObjectMapping* mapping = [RKManagedObjectMapping mappingForEntityWithName:@"RKCat" inManagedObjectStore:store]; + RKManagedObjectMapping *mapping = [RKManagedObjectMapping mappingForEntityWithName:@"RKCat" inManagedObjectStore:store]; id value = [mapping defaultValueForMissingAttribute:@"name"]; assertThat(value, is(equalTo(@"Kitty Cat!"))); } -- (void)testShouldCreateNewInstancesOfUnmanagedObjects { +- (void)testShouldCreateNewInstancesOfUnmanagedObjects +{ [RKTestFactory managedObjectStore]; - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKMappableObject class]]; + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKMappableObject class]]; id object = [mapping mappableObjectForData:[NSDictionary dictionary]]; assertThat(object, isNot(nilValue())); assertThat([object class], is(equalTo([RKMappableObject class]))); } -- (void)testShouldCreateNewInstancesOfManagedObjectsWhenTheMappingIsAnRKObjectMapping { +- (void)testShouldCreateNewInstancesOfManagedObjectsWhenTheMappingIsAnRKObjectMapping +{ [RKTestFactory managedObjectStore]; - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKMappableObject class]]; + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKMappableObject class]]; id object = [mapping mappableObjectForData:[NSDictionary dictionary]]; assertThat(object, isNot(nilValue())); assertThat([object class], is(equalTo([RKMappableObject class]))); } -- (void)testShouldCreateNewManagedObjectInstancesWhenThereIsNoPrimaryKeyInTheData { +- (void)testShouldCreateNewManagedObjectInstancesWhenThereIsNoPrimaryKeyInTheData +{ RKManagedObjectStore *store = [RKTestFactory managedObjectStore]; - RKManagedObjectMapping* mapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:store]; + RKManagedObjectMapping *mapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:store]; mapping.primaryKeyAttribute = @"railsID"; - NSDictionary* data = [NSDictionary dictionary]; + NSDictionary *data = [NSDictionary dictionary]; id object = [mapping mappableObjectForData:data]; assertThat(object, isNot(nilValue())); assertThat(object, is(instanceOf([RKHuman class]))); } -- (void)testShouldCreateNewManagedObjectInstancesWhenThereIsNoPrimaryKeyAttribute { +- (void)testShouldCreateNewManagedObjectInstancesWhenThereIsNoPrimaryKeyAttribute +{ RKManagedObjectStore *store = [RKTestFactory managedObjectStore]; - RKManagedObjectMapping* mapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:store]; + RKManagedObjectMapping *mapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:store]; - NSDictionary* data = [NSDictionary dictionary]; + NSDictionary *data = [NSDictionary dictionary]; id object = [mapping mappableObjectForData:data]; assertThat(object, isNot(nilValue())); assertThat(object, is(instanceOf([RKHuman class]))); } -- (void)testShouldCreateANewManagedObjectWhenThePrimaryKeyValueIsNSNull { +- (void)testShouldCreateANewManagedObjectWhenThePrimaryKeyValueIsNSNull +{ RKManagedObjectStore *store = [RKTestFactory managedObjectStore]; - RKManagedObjectMapping* mapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:store]; + RKManagedObjectMapping *mapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:store]; mapping.primaryKeyAttribute = @"railsID"; [mapping addAttributeMapping:[RKObjectAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"railsID"]]; - NSDictionary* data = [NSDictionary dictionaryWithObject:[NSNull null] forKey:@"id"]; + NSDictionary *data = [NSDictionary dictionaryWithObject:[NSNull null] forKey:@"id"]; id object = [mapping mappableObjectForData:data]; assertThat(object, isNot(nilValue())); assertThat(object, is(instanceOf([RKHuman class]))); } -- (void)testShouldMapACollectionOfObjectsWithDynamicKeys { +- (void)testShouldMapACollectionOfObjectsWithDynamicKeys +{ RKManagedObjectStore *objectStore = [RKTestFactory managedObjectStore]; RKManagedObjectMapping *mapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:objectStore]; mapping.forceCollectionMapping = YES; @@ -121,26 +128,27 @@ - (void)testShouldMapACollectionOfObjectsWithDynamicKeys { value:@"rachit" inManagedObjectContext:objectStore.primaryManagedObjectContext]; id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"DynamicKeys.json"]; - RKObjectMapper* mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; + RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; [mapper performMapping]; [mockCacheStrategy verify]; } -- (void)testShouldPickTheAppropriateMappingBasedOnAnAttributeValue { +- (void)testShouldPickTheAppropriateMappingBasedOnAnAttributeValue +{ RKManagedObjectStore *objectStore = [RKTestFactory managedObjectStore]; - RKDynamicObjectMapping* dynamicMapping = [RKDynamicObjectMapping dynamicMapping]; - RKManagedObjectMapping* childMapping = [RKManagedObjectMapping mappingForClass:[RKChild class] inManagedObjectStore:objectStore]; + RKDynamicObjectMapping *dynamicMapping = [RKDynamicObjectMapping dynamicMapping]; + RKManagedObjectMapping *childMapping = [RKManagedObjectMapping mappingForClass:[RKChild class] inManagedObjectStore:objectStore]; childMapping.primaryKeyAttribute = @"railsID"; [childMapping mapAttributes:@"name", nil]; - RKManagedObjectMapping* parentMapping = [RKManagedObjectMapping mappingForClass:[RKParent class] inManagedObjectStore:objectStore]; + RKManagedObjectMapping *parentMapping = [RKManagedObjectMapping mappingForClass:[RKParent class] inManagedObjectStore:objectStore]; parentMapping.primaryKeyAttribute = @"railsID"; [parentMapping mapAttributes:@"name", @"age", nil]; [dynamicMapping setObjectMapping:parentMapping whenValueOfKeyPath:@"type" isEqualTo:@"Parent"]; [dynamicMapping setObjectMapping:childMapping whenValueOfKeyPath:@"type" isEqualTo:@"Child"]; - RKObjectMapping* mapping = [dynamicMapping objectMappingForDictionary:[RKTestFixture parsedObjectWithContentsOfFixture:@"parent.json"]]; + RKObjectMapping *mapping = [dynamicMapping objectMappingForDictionary:[RKTestFixture parsedObjectWithContentsOfFixture:@"parent.json"]]; assertThat(mapping, is(notNilValue())); assertThatBool([mapping isKindOfClass:[RKManagedObjectMapping class]], is(equalToBool(YES))); assertThat(NSStringFromClass(mapping.objectClass), is(equalTo(@"RKParent"))); @@ -150,7 +158,8 @@ - (void)testShouldPickTheAppropriateMappingBasedOnAnAttributeValue { assertThat(NSStringFromClass(mapping.objectClass), is(equalTo(@"RKChild"))); } -- (void)testShouldIncludeTransformableAttributesInPropertyNamesAndTypes { +- (void)testShouldIncludeTransformableAttributesInPropertyNamesAndTypes +{ [RKTestFactory managedObjectStore]; NSDictionary *attributesByName = [[RKHuman entity] attributesByName]; NSDictionary *propertiesByName = [[RKHuman entity] propertiesByName]; @@ -163,14 +172,16 @@ - (void)testShouldIncludeTransformableAttributesInPropertyNamesAndTypes { assertThat([propertyNamesAndTypes objectForKey:@"favoriteColors"], is(notNilValue())); } -- (void)testThatAssigningAnEntityWithANonNilPrimaryKeyAttributeSetsTheDefaultValueForTheMapping { +- (void)testThatAssigningAnEntityWithANonNilPrimaryKeyAttributeSetsTheDefaultValueForTheMapping +{ RKManagedObjectStore *store = [RKTestFactory managedObjectStore]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"RKCat" inManagedObjectContext:store.primaryManagedObjectContext]; RKManagedObjectMapping *mapping = [RKManagedObjectMapping mappingForEntity:entity inManagedObjectStore:store]; assertThat(mapping.primaryKeyAttribute, is(equalTo(@"railsID"))); } -- (void)testThatAssigningAPrimaryKeyAttributeToAMappingWhoseEntityHasANilPrimaryKeyAttributeAssignsItToTheEntity { +- (void)testThatAssigningAPrimaryKeyAttributeToAMappingWhoseEntityHasANilPrimaryKeyAttributeAssignsItToTheEntity +{ RKManagedObjectStore *store = [RKTestFactory managedObjectStore]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"RKCloud" inManagedObjectContext:store.primaryManagedObjectContext]; RKManagedObjectMapping *mapping = [RKManagedObjectMapping mappingForEntity:entity inManagedObjectStore:store]; @@ -182,40 +193,42 @@ - (void)testThatAssigningAPrimaryKeyAttributeToAMappingWhoseEntityHasANilPrimary #pragma mark - Fetched Results Cache -- (void)testShouldFindExistingManagedObjectsByPrimaryKeyWithFetchedResultsCache { - RKManagedObjectStore* store = [RKTestFactory managedObjectStore]; +- (void)testShouldFindExistingManagedObjectsByPrimaryKeyWithFetchedResultsCache +{ + RKManagedObjectStore *store = [RKTestFactory managedObjectStore]; store.cacheStrategy = [RKFetchRequestManagedObjectCache new]; - RKManagedObjectMapping* mapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:store]; + RKManagedObjectMapping *mapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:store]; mapping.primaryKeyAttribute = @"railsID"; [mapping addAttributeMapping:[RKObjectAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"railsID"]]; - RKHuman* human = [RKHuman object]; + RKHuman *human = [RKHuman object]; human.railsID = [NSNumber numberWithInt:123]; [store save:nil]; assertThatBool([RKHuman hasAtLeastOneEntity], is(equalToBool(YES))); - NSDictionary* data = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:123] forKey:@"id"]; + NSDictionary *data = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:123] forKey:@"id"]; id object = [mapping mappableObjectForData:data]; assertThat(object, isNot(nilValue())); assertThat(object, is(equalTo(human))); } -- (void)testShouldFindExistingManagedObjectsByPrimaryKeyPathWithFetchedResultsCache { - RKManagedObjectStore* store = [RKTestFactory managedObjectStore]; +- (void)testShouldFindExistingManagedObjectsByPrimaryKeyPathWithFetchedResultsCache +{ + RKManagedObjectStore *store = [RKTestFactory managedObjectStore]; store.cacheStrategy = [RKFetchRequestManagedObjectCache new]; [RKHuman truncateAll]; - RKManagedObjectMapping* mapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:store]; + RKManagedObjectMapping *mapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:store]; mapping.primaryKeyAttribute = @"railsID"; [mapping addAttributeMapping:[RKObjectAttributeMapping mappingFromKeyPath:@"monkey.id" toKeyPath:@"railsID"]]; [RKHuman truncateAll]; - RKHuman* human = [RKHuman object]; + RKHuman *human = [RKHuman object]; human.railsID = [NSNumber numberWithInt:123]; [store save:nil]; assertThatBool([RKHuman hasAtLeastOneEntity], is(equalToBool(YES))); - NSDictionary* data = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:123] forKey:@"id"]; - NSDictionary* nestedDictionary = [NSDictionary dictionaryWithObject:data forKey:@"monkey"]; + NSDictionary *data = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:123] forKey:@"id"]; + NSDictionary *nestedDictionary = [NSDictionary dictionaryWithObject:data forKey:@"monkey"]; id object = [mapping mappableObjectForData:nestedDictionary]; assertThat(object, isNot(nilValue())); assertThat(object, is(equalTo(human))); @@ -223,43 +236,45 @@ - (void)testShouldFindExistingManagedObjectsByPrimaryKeyPathWithFetchedResultsCa #pragma mark - In Memory Cache -- (void)testShouldFindExistingManagedObjectsByPrimaryKeyWithInMemoryCache { - RKManagedObjectStore* store = [RKTestFactory managedObjectStore]; +- (void)testShouldFindExistingManagedObjectsByPrimaryKeyWithInMemoryCache +{ + RKManagedObjectStore *store = [RKTestFactory managedObjectStore]; [RKHuman truncateAllInContext:store.primaryManagedObjectContext]; store.cacheStrategy = [RKInMemoryManagedObjectCache new]; - RKManagedObjectMapping* mapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:store]; + RKManagedObjectMapping *mapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:store]; mapping.primaryKeyAttribute = @"railsID"; [mapping addAttributeMapping:[RKObjectAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"railsID"]]; - RKHuman* human = [RKHuman createInContext:store.primaryManagedObjectContext]; + RKHuman *human = [RKHuman createInContext:store.primaryManagedObjectContext]; human.railsID = [NSNumber numberWithInt:123]; [store save:nil]; assertThatBool([RKHuman hasAtLeastOneEntity], is(equalToBool(YES))); - NSDictionary* data = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:123] forKey:@"id"]; + NSDictionary *data = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:123] forKey:@"id"]; NSManagedObject *object = [mapping mappableObjectForData:data]; assertThat([object managedObjectContext], is(equalTo(store.primaryManagedObjectContext))); assertThat(object, isNot(nilValue())); assertThat(object, is(equalTo(human))); } -- (void)testShouldFindExistingManagedObjectsByPrimaryKeyPathWithInMemoryCache { - RKManagedObjectStore* store = [RKTestFactory managedObjectStore]; +- (void)testShouldFindExistingManagedObjectsByPrimaryKeyPathWithInMemoryCache +{ + RKManagedObjectStore *store = [RKTestFactory managedObjectStore]; [RKHuman truncateAllInContext:store.primaryManagedObjectContext]; store.cacheStrategy = [RKInMemoryManagedObjectCache new]; [RKHuman truncateAll]; - RKManagedObjectMapping* mapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:store]; + RKManagedObjectMapping *mapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:store]; mapping.primaryKeyAttribute = @"railsID"; [mapping addAttributeMapping:[RKObjectAttributeMapping mappingFromKeyPath:@"monkey.id" toKeyPath:@"railsID"]]; [RKHuman truncateAll]; - RKHuman* human = [RKHuman object]; + RKHuman *human = [RKHuman object]; human.railsID = [NSNumber numberWithInt:123]; [store save:nil]; assertThatBool([RKHuman hasAtLeastOneEntity], is(equalToBool(YES))); - NSDictionary* data = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:123] forKey:@"id"]; - NSDictionary* nestedDictionary = [NSDictionary dictionaryWithObject:data forKey:@"monkey"]; + NSDictionary *data = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:123] forKey:@"id"]; + NSDictionary *nestedDictionary = [NSDictionary dictionaryWithObject:data forKey:@"monkey"]; id object = [mapping mappableObjectForData:nestedDictionary]; assertThat(object, isNot(nilValue())); assertThat(object, is(equalTo(human))); @@ -267,22 +282,22 @@ - (void)testShouldFindExistingManagedObjectsByPrimaryKeyPathWithInMemoryCache { - (void)testMappingWithFetchRequestCacheWherePrimaryKeyAttributeOfMappingDisagreesWithEntity { - RKManagedObjectStore* store = [RKTestFactory managedObjectStore]; + RKManagedObjectStore *store = [RKTestFactory managedObjectStore]; store.cacheStrategy = [RKFetchRequestManagedObjectCache new]; [RKHuman truncateAll]; - RKManagedObjectMapping* mapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:store]; + RKManagedObjectMapping *mapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:store]; mapping.primaryKeyAttribute = @"name"; [RKHuman entity].primaryKeyAttributeName = @"railsID"; [mapping addAttributeMapping:[RKObjectAttributeMapping mappingFromKeyPath:@"monkey.name" toKeyPath:@"name"]]; [RKHuman truncateAll]; - RKHuman* human = [RKHuman object]; + RKHuman *human = [RKHuman object]; human.name = @"Testing"; [store save:nil]; assertThatBool([RKHuman hasAtLeastOneEntity], is(equalToBool(YES))); - NSDictionary* data = [NSDictionary dictionaryWithObject:@"Testing" forKey:@"name"]; - NSDictionary* nestedDictionary = [NSDictionary dictionaryWithObject:data forKey:@"monkey"]; + NSDictionary *data = [NSDictionary dictionaryWithObject:@"Testing" forKey:@"name"]; + NSDictionary *nestedDictionary = [NSDictionary dictionaryWithObject:data forKey:@"monkey"]; id object = [mapping mappableObjectForData:nestedDictionary]; assertThat(object, isNot(nilValue())); assertThat(object, is(equalTo(human))); @@ -293,22 +308,22 @@ - (void)testMappingWithFetchRequestCacheWherePrimaryKeyAttributeOfMappingDisagre - (void)testMappingWithInMemoryCacheWherePrimaryKeyAttributeOfMappingDisagreesWithEntity { - RKManagedObjectStore* store = [RKTestFactory managedObjectStore]; + RKManagedObjectStore *store = [RKTestFactory managedObjectStore]; store.cacheStrategy = [RKInMemoryManagedObjectCache new]; [RKHuman truncateAll]; - RKManagedObjectMapping* mapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:store]; + RKManagedObjectMapping *mapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:store]; mapping.primaryKeyAttribute = @"name"; [RKHuman entity].primaryKeyAttributeName = @"railsID"; [mapping addAttributeMapping:[RKObjectAttributeMapping mappingFromKeyPath:@"monkey.name" toKeyPath:@"name"]]; [RKHuman truncateAll]; - RKHuman* human = [RKHuman object]; + RKHuman *human = [RKHuman object]; human.name = @"Testing"; [store save:nil]; assertThatBool([RKHuman hasAtLeastOneEntity], is(equalToBool(YES))); - NSDictionary* data = [NSDictionary dictionaryWithObject:@"Testing" forKey:@"name"]; - NSDictionary* nestedDictionary = [NSDictionary dictionaryWithObject:data forKey:@"monkey"]; + NSDictionary *data = [NSDictionary dictionaryWithObject:@"Testing" forKey:@"name"]; + NSDictionary *nestedDictionary = [NSDictionary dictionaryWithObject:data forKey:@"monkey"]; id object = [mapping mappableObjectForData:nestedDictionary]; assertThat(object, isNot(nilValue())); assertThat(object, is(equalTo(human))); @@ -319,24 +334,24 @@ - (void)testMappingWithInMemoryCacheWherePrimaryKeyAttributeOfMappingDisagreesWi - (void)testThatCreationOfNewObjectWithIncorrectTypeValueForPrimaryKeyAddsToCache { - RKManagedObjectStore* store = [RKTestFactory managedObjectStore]; + RKManagedObjectStore *store = [RKTestFactory managedObjectStore]; store.cacheStrategy = [RKInMemoryManagedObjectCache new]; [RKHuman truncateAll]; - RKManagedObjectMapping* mapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:store]; + RKManagedObjectMapping *mapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:store]; mapping.primaryKeyAttribute = @"railsID"; [RKHuman entity].primaryKeyAttributeName = @"railsID"; [mapping addAttributeMapping:[RKObjectAttributeMapping mappingFromKeyPath:@"monkey.name" toKeyPath:@"name"]]; [mapping addAttributeMapping:[RKObjectAttributeMapping mappingFromKeyPath:@"monkey.railsID" toKeyPath:@"railsID"]]; - + [RKHuman truncateAll]; - RKHuman* human = [RKHuman object]; + RKHuman *human = [RKHuman object]; human.name = @"Testing"; human.railsID = [NSNumber numberWithInteger:12345]; [store save:nil]; assertThatBool([RKHuman hasAtLeastOneEntity], is(equalToBool(YES))); - - NSDictionary* data = [NSDictionary dictionaryWithObject:@"12345" forKey:@"railsID"]; - NSDictionary* nestedDictionary = [NSDictionary dictionaryWithObject:data forKey:@"monkey"]; + + NSDictionary *data = [NSDictionary dictionaryWithObject:@"12345" forKey:@"railsID"]; + NSDictionary *nestedDictionary = [NSDictionary dictionaryWithObject:data forKey:@"monkey"]; RKHuman *object = [mapping mappableObjectForData:nestedDictionary]; assertThat(object, isNot(nilValue())); assertThat(object, is(equalTo(human))); diff --git a/Tests/Logic/CoreData/RKManagedObjectThreadSafeInvocationTest.m b/Tests/Logic/CoreData/RKManagedObjectThreadSafeInvocationTest.m index 1c9fc704f6..4e41b55e0f 100644 --- a/Tests/Logic/CoreData/RKManagedObjectThreadSafeInvocationTest.m +++ b/Tests/Logic/CoreData/RKManagedObjectThreadSafeInvocationTest.m @@ -23,8 +23,8 @@ #import "RKManagedObjectThreadSafeInvocation.h" @interface RKManagedObjectThreadSafeInvocationTest : RKTestCase { - NSMutableDictionary* _dictionary; - RKManagedObjectStore* _objectStore; + NSMutableDictionary *_dictionary; + RKManagedObjectStore *_objectStore; id _results; BOOL _waiting; } @@ -33,79 +33,85 @@ @interface RKManagedObjectThreadSafeInvocationTest : RKTestCase { @implementation RKManagedObjectThreadSafeInvocationTest -- (void)testShouldSerializeOneManagedObjectToManagedObjectID { - RKManagedObjectStore* objectStore = [RKTestFactory managedObjectStore]; +- (void)testShouldSerializeOneManagedObjectToManagedObjectID +{ + RKManagedObjectStore *objectStore = [RKTestFactory managedObjectStore]; RKObjectManager *objectManager = [RKTestFactory objectManager]; objectManager.objectStore = objectStore; - RKHuman* human = [RKHuman object]; - NSMutableDictionary* dictionary = [NSMutableDictionary dictionaryWithObject:human forKey:@"human"]; - NSMethodSignature* signature = [self methodSignatureForSelector:@selector(informDelegateWithDictionary:)]; - RKManagedObjectThreadSafeInvocation* invocation = [RKManagedObjectThreadSafeInvocation invocationWithMethodSignature:signature]; + RKHuman *human = [RKHuman object]; + NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithObject:human forKey:@"human"]; + NSMethodSignature *signature = [self methodSignatureForSelector:@selector(informDelegateWithDictionary:)]; + RKManagedObjectThreadSafeInvocation *invocation = [RKManagedObjectThreadSafeInvocation invocationWithMethodSignature:signature]; [invocation serializeManagedObjectsForArgument:dictionary withKeyPaths:[NSSet setWithObject:@"human"]]; assertThat([dictionary valueForKeyPath:@"human"], is(instanceOf([NSManagedObjectID class]))); } -- (void)testShouldSerializeOneManagedObjectWithKeyPathToManagedObjectID { +- (void)testShouldSerializeOneManagedObjectWithKeyPathToManagedObjectID +{ NSString *testKey = @"data.human"; - RKManagedObjectStore* objectStore = [RKTestFactory managedObjectStore]; + RKManagedObjectStore *objectStore = [RKTestFactory managedObjectStore]; RKObjectManager *objectManager = [RKTestFactory objectManager]; objectManager.objectStore = objectStore; - RKHuman* human = [RKHuman object]; - NSMutableDictionary* dictionary = [NSMutableDictionary dictionaryWithObject:human forKey:testKey]; - NSMethodSignature* signature = [self methodSignatureForSelector:@selector(informDelegateWithDictionary:)]; - RKManagedObjectThreadSafeInvocation* invocation = [RKManagedObjectThreadSafeInvocation invocationWithMethodSignature:signature]; + RKHuman *human = [RKHuman object]; + NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithObject:human forKey:testKey]; + NSMethodSignature *signature = [self methodSignatureForSelector:@selector(informDelegateWithDictionary:)]; + RKManagedObjectThreadSafeInvocation *invocation = [RKManagedObjectThreadSafeInvocation invocationWithMethodSignature:signature]; [invocation serializeManagedObjectsForArgument:dictionary withKeyPaths:[NSSet setWithObject:testKey]]; assertThat([dictionary valueForKeyPath:testKey], is(instanceOf([NSManagedObjectID class]))); } -- (void)testShouldSerializeCollectionOfManagedObjectsToManagedObjectIDs { - RKManagedObjectStore* objectStore = [RKTestFactory managedObjectStore]; +- (void)testShouldSerializeCollectionOfManagedObjectsToManagedObjectIDs +{ + RKManagedObjectStore *objectStore = [RKTestFactory managedObjectStore]; RKObjectManager *objectManager = [RKTestFactory objectManager]; objectManager.objectStore = objectStore; - RKHuman* human1 = [RKHuman object]; - RKHuman* human2 = [RKHuman object]; - NSArray* humans = [NSArray arrayWithObjects:human1, human2, nil]; - NSMutableDictionary* dictionary = [NSMutableDictionary dictionaryWithObject:humans forKey:@"humans"]; - NSMethodSignature* signature = [self methodSignatureForSelector:@selector(informDelegateWithDictionary:)]; - RKManagedObjectThreadSafeInvocation* invocation = [RKManagedObjectThreadSafeInvocation invocationWithMethodSignature:signature]; + RKHuman *human1 = [RKHuman object]; + RKHuman *human2 = [RKHuman object]; + NSArray *humans = [NSArray arrayWithObjects:human1, human2, nil]; + NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithObject:humans forKey:@"humans"]; + NSMethodSignature *signature = [self methodSignatureForSelector:@selector(informDelegateWithDictionary:)]; + RKManagedObjectThreadSafeInvocation *invocation = [RKManagedObjectThreadSafeInvocation invocationWithMethodSignature:signature]; [invocation serializeManagedObjectsForArgument:dictionary withKeyPaths:[NSSet setWithObject:@"humans"]]; assertThat([dictionary valueForKeyPath:@"humans"], is(instanceOf([NSArray class]))); assertThat([[dictionary valueForKeyPath:@"humans"] lastObject], is(instanceOf([NSManagedObjectID class]))); } -- (void)testShouldDeserializeOneManagedObjectIDToManagedObject { - RKManagedObjectStore* objectStore = [RKTestFactory managedObjectStore]; +- (void)testShouldDeserializeOneManagedObjectIDToManagedObject +{ + RKManagedObjectStore *objectStore = [RKTestFactory managedObjectStore]; RKObjectManager *objectManager = [RKTestFactory objectManager]; objectManager.objectStore = objectStore; - RKHuman* human = [RKHuman object]; - NSMutableDictionary* dictionary = [NSMutableDictionary dictionaryWithObject:[human objectID] forKey:@"human"]; - NSMethodSignature* signature = [self methodSignatureForSelector:@selector(informDelegateWithDictionary:)]; - RKManagedObjectThreadSafeInvocation* invocation = [RKManagedObjectThreadSafeInvocation invocationWithMethodSignature:signature]; + RKHuman *human = [RKHuman object]; + NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithObject:[human objectID] forKey:@"human"]; + NSMethodSignature *signature = [self methodSignatureForSelector:@selector(informDelegateWithDictionary:)]; + RKManagedObjectThreadSafeInvocation *invocation = [RKManagedObjectThreadSafeInvocation invocationWithMethodSignature:signature]; invocation.objectStore = objectStore; [invocation deserializeManagedObjectIDsForArgument:dictionary withKeyPaths:[NSSet setWithObject:@"human"]]; assertThat([dictionary valueForKeyPath:@"human"], is(instanceOf([NSManagedObject class]))); assertThat([dictionary valueForKeyPath:@"human"], is(equalTo(human))); } -- (void)testShouldDeserializeCollectionOfManagedObjectIDToManagedObjects { - RKManagedObjectStore* objectStore = [RKTestFactory managedObjectStore]; +- (void)testShouldDeserializeCollectionOfManagedObjectIDToManagedObjects +{ + RKManagedObjectStore *objectStore = [RKTestFactory managedObjectStore]; RKObjectManager *objectManager = [RKTestFactory objectManager]; objectManager.objectStore = objectStore; - RKHuman* human1 = [RKHuman object]; - RKHuman* human2 = [RKHuman object]; - NSArray* humanIDs = [NSArray arrayWithObjects:[human1 objectID], [human2 objectID], nil]; - NSMutableDictionary* dictionary = [NSMutableDictionary dictionaryWithObject:humanIDs forKey:@"humans"]; - NSMethodSignature* signature = [self methodSignatureForSelector:@selector(informDelegateWithDictionary:)]; - RKManagedObjectThreadSafeInvocation* invocation = [RKManagedObjectThreadSafeInvocation invocationWithMethodSignature:signature]; + RKHuman *human1 = [RKHuman object]; + RKHuman *human2 = [RKHuman object]; + NSArray *humanIDs = [NSArray arrayWithObjects:[human1 objectID], [human2 objectID], nil]; + NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithObject:humanIDs forKey:@"humans"]; + NSMethodSignature *signature = [self methodSignatureForSelector:@selector(informDelegateWithDictionary:)]; + RKManagedObjectThreadSafeInvocation *invocation = [RKManagedObjectThreadSafeInvocation invocationWithMethodSignature:signature]; invocation.objectStore = objectStore; [invocation deserializeManagedObjectIDsForArgument:dictionary withKeyPaths:[NSSet setWithObject:@"humans"]]; assertThat([dictionary valueForKeyPath:@"humans"], is(instanceOf([NSArray class]))); - NSArray* humans = [NSArray arrayWithObjects:human1, human2, nil]; + NSArray *humans = [NSArray arrayWithObjects:human1, human2, nil]; assertThat([dictionary valueForKeyPath:@"humans"], is(equalTo(humans))); } -- (void)informDelegateWithDictionary:(NSDictionary*)results { +- (void)informDelegateWithDictionary:(NSDictionary *)results +{ assertThatBool([NSThread isMainThread], equalToBool(YES)); assertThat(results, isNot(nilValue())); assertThat(results, isNot(empty())); @@ -113,18 +119,19 @@ - (void)informDelegateWithDictionary:(NSDictionary*)results { _waiting = NO; } -- (void)createBackgroundObjects { - NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; +- (void)createBackgroundObjects +{ + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; assertThatBool([NSThread isMainThread], equalToBool(NO)); // Assert this is not the main thread // Create a new array of objects in the background RKObjectManager *objectManager = [RKTestFactory objectManager]; objectManager.objectStore = [RKTestFactory managedObjectStore]; - NSArray* humans = [NSArray arrayWithObject:[RKHuman object]]; + NSArray *humans = [NSArray arrayWithObject:[RKHuman object]]; _dictionary = [[NSMutableDictionary dictionaryWithObject:humans forKey:@"humans"] retain]; - NSMethodSignature* signature = [self methodSignatureForSelector:@selector(informDelegateWithDictionary:)]; - RKManagedObjectThreadSafeInvocation* invocation = [RKManagedObjectThreadSafeInvocation invocationWithMethodSignature:signature]; + NSMethodSignature *signature = [self methodSignatureForSelector:@selector(informDelegateWithDictionary:)]; + RKManagedObjectThreadSafeInvocation *invocation = [RKManagedObjectThreadSafeInvocation invocationWithMethodSignature:signature]; invocation.objectStore = _objectStore; [invocation retain]; [invocation setTarget:self]; @@ -136,7 +143,8 @@ - (void)createBackgroundObjects { [pool drain]; } -- (void)testShouldSerializeAndDeserializeManagedObjectsAcrossAThreadInvocation { +- (void)testShouldSerializeAndDeserializeManagedObjectsAcrossAThreadInvocation +{ _objectStore = [[RKTestFactory managedObjectStore] retain]; _waiting = YES; [self performSelectorInBackground:@selector(createBackgroundObjects) withObject:nil]; diff --git a/Tests/Logic/CoreData/RKSearchWordObserverTest.m b/Tests/Logic/CoreData/RKSearchWordObserverTest.m index 1c66295616..9ba344f606 100644 --- a/Tests/Logic/CoreData/RKSearchWordObserverTest.m +++ b/Tests/Logic/CoreData/RKSearchWordObserverTest.m @@ -16,14 +16,16 @@ @interface RKSearchWordObserverTest : RKTestCase @implementation RKSearchWordObserverTest -- (void)testInstantiateASearchWordObserverOnObjectStoreInit { +- (void)testInstantiateASearchWordObserverOnObjectStoreInit +{ [RKTestFactory managedObjectStore]; assertThat([RKSearchWordObserver sharedObserver], isNot(nil)); } -- (void)testTriggerSearchWordRegenerationForChagedSearchableValuesAtObjectContextSaveTime { - RKManagedObjectStore* store = [RKTestFactory managedObjectStore]; - RKSearchable* searchable = [RKSearchable createEntity]; +- (void)testTriggerSearchWordRegenerationForChagedSearchableValuesAtObjectContextSaveTime +{ + RKManagedObjectStore *store = [RKTestFactory managedObjectStore]; + RKSearchable *searchable = [RKSearchable createEntity]; searchable.title = @"This is the title of my new object"; assertThat(searchable.searchWords, is(empty())); [store save:nil]; diff --git a/Tests/Logic/CoreData/RKSearchableManagedObjectTest.m b/Tests/Logic/CoreData/RKSearchableManagedObjectTest.m index 3a75dd7b6e..4e618458ca 100644 --- a/Tests/Logic/CoreData/RKSearchableManagedObjectTest.m +++ b/Tests/Logic/CoreData/RKSearchableManagedObjectTest.m @@ -16,15 +16,16 @@ @interface RKSearchableManagedObjectTest : RKTestCase @implementation RKSearchableManagedObjectTest -- (void)testGenerateSearchWordsForSearchableObjects { +- (void)testGenerateSearchWordsForSearchableObjects +{ [RKTestFactory managedObjectStore]; - RKSearchable* searchable = [RKSearchable createEntity]; + RKSearchable *searchable = [RKSearchable createEntity]; searchable.title = @"This is the title of my new object"; searchable.body = @"This is the point at which I begin pontificating at length about various and sundry things for no real reason at all. Furthermore, ..."; assertThat(searchable.searchWords, is(empty())); [searchable refreshSearchWords]; assertThat(searchable.searchWords, isNot(empty())); - NSArray* words = [[[searchable.searchWords valueForKey:@"word"] allObjects] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; + NSArray *words = [[[searchable.searchWords valueForKey:@"word"] allObjects] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; assertThat([words componentsJoinedByString:@", "], is(equalTo(@"about, all, and, at, begin, for, furthermore, i, is, length, my, new, no, object, of, point, pontificating, real, reason, sundry, the, things, this, title, various, which"))); } diff --git a/Tests/Logic/Network/RKAuthenticationTest.m b/Tests/Logic/Network/RKAuthenticationTest.m index c55d9a2e3d..e025d1e393 100644 --- a/Tests/Logic/Network/RKAuthenticationTest.m +++ b/Tests/Logic/Network/RKAuthenticationTest.m @@ -21,8 +21,8 @@ #import "RKTestEnvironment.h" #import "RKClient.h" -static NSString* const RKAuthenticationTestUsername = @"restkit"; -static NSString* const RKAuthenticationTestPassword = @"authentication"; +static NSString * const RKAuthenticationTestUsername = @"restkit"; +static NSString * const RKAuthenticationTestPassword = @"authentication"; @interface RKAuthenticationTest : RKTestCase { @@ -32,17 +32,19 @@ @interface RKAuthenticationTest : RKTestCase { @implementation RKAuthenticationTest -- (void)testShouldAccessUnprotectedResourcePaths { - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; - RKClient* client = [RKTestFactory client]; +- (void)testShouldAccessUnprotectedResourcePaths +{ + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; + RKClient *client = [RKTestFactory client]; [client get:@"/authentication/none" delegate:loader]; [loader waitForResponse]; assertThatBool([loader.response isOK], is(equalToBool(YES))); } -- (void)testShouldAuthenticateViaHTTPAuthBasic { - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; - RKClient* client = [RKTestFactory client]; +- (void)testShouldAuthenticateViaHTTPAuthBasic +{ + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; + RKClient *client = [RKTestFactory client]; client.username = RKAuthenticationTestUsername; client.password = RKAuthenticationTestPassword; [client get:@"/authentication/basic" delegate:loader]; @@ -50,9 +52,10 @@ - (void)testShouldAuthenticateViaHTTPAuthBasic { assertThatBool([loader.response isOK], is(equalToBool(YES))); } -- (void)testShouldFailAuthenticationWithInvalidCredentialsForHTTPAuthBasic { - RKTestResponseLoader* loader = [RKTestResponseLoader new]; - RKClient* client = [RKTestFactory client]; +- (void)testShouldFailAuthenticationWithInvalidCredentialsForHTTPAuthBasic +{ + RKTestResponseLoader *loader = [RKTestResponseLoader new]; + RKClient *client = [RKTestFactory client]; client.username = RKAuthenticationTestUsername; client.password = @"INVALID"; [client get:@"/authentication/basic" delegate:loader]; @@ -64,9 +67,10 @@ - (void)testShouldFailAuthenticationWithInvalidCredentialsForHTTPAuthBasic { [loader release]; } -- (void)testShouldAuthenticateViaHTTPAuthDigest { - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; - RKClient* client = [RKTestFactory client]; +- (void)testShouldAuthenticateViaHTTPAuthDigest +{ + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; + RKClient *client = [RKTestFactory client]; client.username = RKAuthenticationTestUsername; client.password = RKAuthenticationTestPassword; [client get:@"/authentication/digest" delegate:loader]; diff --git a/Tests/Logic/Network/RKClientTest.m b/Tests/Logic/Network/RKClientTest.m index d746156541..988e26b659 100644 --- a/Tests/Logic/Network/RKClientTest.m +++ b/Tests/Logic/Network/RKClientTest.m @@ -28,23 +28,27 @@ @interface RKClientTest : RKTestCase @implementation RKClientTest -- (void)setUp { +- (void)setUp +{ [RKTestFactory setUp]; } -- (void)tearDown { +- (void)tearDown +{ [RKTestFactory tearDown]; } -- (void)testShouldDetectNetworkStatusWithAHostname { - RKClient* client = [[RKClient alloc] initWithBaseURLString:@"http://restkit.org"]; +- (void)testShouldDetectNetworkStatusWithAHostname +{ + RKClient *client = [[RKClient alloc] initWithBaseURLString:@"http://restkit.org"]; [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.3]]; // Let the runloop cycle RKReachabilityNetworkStatus status = [client.reachabilityObserver networkStatus]; assertThatInt(status, is(equalToInt(RKReachabilityReachableViaWiFi))); [client release]; } -- (void)testShouldDetectNetworkStatusWithAnIPAddressBaseName { +- (void)testShouldDetectNetworkStatusWithAnIPAddressBaseName +{ RKClient *client = [[RKClient alloc] initWithBaseURLString:@"http://173.45.234.197"]; [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.3]]; // Let the runloop cycle RKReachabilityNetworkStatus status = [client.reachabilityObserver networkStatus]; @@ -52,25 +56,28 @@ - (void)testShouldDetectNetworkStatusWithAnIPAddressBaseName { [client release]; } -- (void)testShouldSetTheCachePolicyOfTheRequest { - RKClient* client = [RKClient clientWithBaseURLString:@"http://restkit.org"]; +- (void)testShouldSetTheCachePolicyOfTheRequest +{ + RKClient *client = [RKClient clientWithBaseURLString:@"http://restkit.org"]; client.cachePolicy = RKRequestCachePolicyLoadIfOffline; - RKRequest* request = [client requestWithResourcePath:@""]; + RKRequest *request = [client requestWithResourcePath:@""]; assertThatInt(request.cachePolicy, is(equalToInt(RKRequestCachePolicyLoadIfOffline))); } -- (void)testShouldInitializeTheCacheOfTheRequest { - RKClient* client = [RKClient clientWithBaseURLString:@"http://restkit.org"]; +- (void)testShouldInitializeTheCacheOfTheRequest +{ + RKClient *client = [RKClient clientWithBaseURLString:@"http://restkit.org"]; client.requestCache = [[[RKRequestCache alloc] init] autorelease]; - RKRequest* request = [client requestWithResourcePath:@""]; + RKRequest *request = [client requestWithResourcePath:@""]; assertThat(request.cache, is(equalTo(client.requestCache))); } -- (void)testShouldLoadPageWithNoContentTypeInformation { - RKClient* client = [RKClient clientWithBaseURLString:@"http://www.semiose.fr"]; +- (void)testShouldLoadPageWithNoContentTypeInformation +{ + RKClient *client = [RKClient clientWithBaseURLString:@"http://www.semiose.fr"]; client.defaultHTTPEncoding = NSISOLatin1StringEncoding; - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; - RKRequest* request = [client requestWithResourcePath:@"/"]; + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; + RKRequest *request = [client requestWithResourcePath:@"/"]; request.delegate = loader; [request send]; [loader waitForResponse]; @@ -79,22 +86,24 @@ - (void)testShouldLoadPageWithNoContentTypeInformation { assertThatInteger([loader.response bodyEncoding], is(equalToInteger(NSISOLatin1StringEncoding))); } -- (void)testShouldAllowYouToChangeTheBaseURL { - RKClient* client = [RKClient clientWithBaseURLString:@"http://www.google.com"]; +- (void)testShouldAllowYouToChangeTheBaseURL +{ + RKClient *client = [RKClient clientWithBaseURLString:@"http://www.google.com"]; [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.3]]; // Let the runloop cycle assertThatBool([client isNetworkReachable], is(equalToBool(YES))); client.baseURL = [RKURL URLWithString:@"http://www.restkit.org"]; [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.3]]; // Let the runloop cycle assertThatBool([client isNetworkReachable], is(equalToBool(YES))); - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; - RKRequest* request = [client requestWithResourcePath:@"/"]; + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; + RKRequest *request = [client requestWithResourcePath:@"/"]; request.delegate = loader; [request send]; [loader waitForResponse]; assertThatBool(loader.wasSuccessful, is(equalToBool(YES))); } -- (void)testShouldLetYouChangeTheHTTPAuthCredentials { +- (void)testShouldLetYouChangeTheHTTPAuthCredentials +{ RKClient *client = [RKTestFactory client]; client.authenticationType = RKRequestAuthenticationTypeHTTP; client.username = @"invalid"; @@ -111,13 +120,15 @@ - (void)testShouldLetYouChangeTheHTTPAuthCredentials { assertThatBool(responseLoader.wasSuccessful, is(equalToBool(YES))); } -- (void)testShouldSuspendTheQueueOnBaseURLChangeWhenReachabilityHasNotBeenEstablished { - RKClient* client = [RKClient clientWithBaseURLString:@"http://www.google.com"]; +- (void)testShouldSuspendTheQueueOnBaseURLChangeWhenReachabilityHasNotBeenEstablished +{ + RKClient *client = [RKClient clientWithBaseURLString:@"http://www.google.com"]; client.baseURL = [RKURL URLWithString:@"http://restkit.org"]; assertThatBool(client.requestQueue.suspended, is(equalToBool(YES))); } -- (void)testShouldNotSuspendTheMainQueueOnBaseURLChangeWhenReachabilityHasBeenEstablished { +- (void)testShouldNotSuspendTheMainQueueOnBaseURLChangeWhenReachabilityHasBeenEstablished +{ RKReachabilityObserver *observer = [RKReachabilityObserver reachabilityObserverForInternet]; [observer getFlags]; assertThatBool([observer isReachabilityDetermined], is(equalToBool(YES))); @@ -127,39 +138,43 @@ - (void)testShouldNotSuspendTheMainQueueOnBaseURLChangeWhenReachabilityHasBeenEs assertThatBool(client.requestQueue.suspended, is(equalToBool(NO))); } -- (void)testShouldAllowYouToChangeTheTimeoutInterval { - RKClient* client = [RKClient clientWithBaseURLString:@"http://restkit.org"]; +- (void)testShouldAllowYouToChangeTheTimeoutInterval +{ + RKClient *client = [RKClient clientWithBaseURLString:@"http://restkit.org"]; client.timeoutInterval = 20.0; - RKRequest* request = [client requestWithResourcePath:@""]; + RKRequest *request = [client requestWithResourcePath:@""]; assertThatFloat(request.timeoutInterval, is(equalToFloat(20.0))); } -- (void)testShouldPerformAPUTWithParams { +- (void)testShouldPerformAPUTWithParams +{ NSLog(@"PENDING ---> FIX ME!!!"); return; - RKClient* client = [RKClient clientWithBaseURLString:@"http://ohblockhero.appspot.com/api/v1"]; + RKClient *client = [RKClient clientWithBaseURLString:@"http://ohblockhero.appspot.com/api/v1"]; client.cachePolicy = RKRequestCachePolicyNone; - RKParams *params=[RKParams params]; + RKParams *params = [RKParams params]; [params setValue:@"username" forParam:@"username"]; [params setValue:@"Dear Daniel" forParam:@"fullName"]; [params setValue:@"aa@aa.com" forParam:@"email"]; - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; [client put:@"/userprofile" params:params delegate:loader]; STAssertNoThrow([loader waitForResponse], @""); [loader waitForResponse]; assertThatBool(loader.wasSuccessful, is(equalToBool(NO))); } -- (void)testShouldAllowYouToChangeTheCacheTimeoutInterval { - RKClient* client = [RKClient clientWithBaseURLString:@"http://restkit.org"]; +- (void)testShouldAllowYouToChangeTheCacheTimeoutInterval +{ + RKClient *client = [RKClient clientWithBaseURLString:@"http://restkit.org"]; client.cacheTimeoutInterval = 20.0; - RKRequest* request = [client requestWithResourcePath:@""]; + RKRequest *request = [client requestWithResourcePath:@""]; assertThatFloat(request.cacheTimeoutInterval, is(equalToFloat(20.0))); } -- (void)testThatRunLoopModePropertyRespected { +- (void)testThatRunLoopModePropertyRespected +{ NSString * const dummyRunLoopMode = @"dummyRunLoopMode"; - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; RKClient *client = [RKTestFactory client]; client.runLoopMode = dummyRunLoopMode; [client get:[[RKTestFactory baseURL] absoluteString] delegate:loader]; diff --git a/Tests/Logic/Network/RKOAuthClientTest.m b/Tests/Logic/Network/RKOAuthClientTest.m index ba88dd12cb..d3ac933938 100644 --- a/Tests/Logic/Network/RKOAuthClientTest.m +++ b/Tests/Logic/Network/RKOAuthClientTest.m @@ -33,7 +33,8 @@ @interface RKOAuthClientTest : RKTestCase @implementation RKOAuthClientTest -- (BOOL)isMongoRunning { +- (BOOL)isMongoRunning +{ static RKPortCheck *portCheck = nil; if (! portCheck) { portCheck = [[RKPortCheck alloc] initWithHost:@"localhost" port:27017]; @@ -43,7 +44,8 @@ - (BOOL)isMongoRunning { return [portCheck isOpen]; } -- (void)testShouldGetAccessToken{ +- (void)testShouldGetAccessToken +{ RKOAuthClientTestSkipWithoutMongoDB(); RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; @@ -55,7 +57,8 @@ - (void)testShouldGetAccessToken{ assertThatBool(loader.wasSuccessful, is(equalToBool(YES))); } -- (void)testShouldNotGetAccessToken { +- (void)testShouldNotGetAccessToken +{ RKOAuthClientTestSkipWithoutMongoDB(); RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; @@ -68,7 +71,8 @@ - (void)testShouldNotGetAccessToken { assertThatBool(loader.wasSuccessful, is(equalToBool(NO))); } -- (void)testShouldGetProtectedResource{ +- (void)testShouldGetProtectedResource +{ RKOAuthClientTestSkipWithoutMongoDB(); //TODO: Encapsulate this code in a correct manner @@ -78,7 +82,7 @@ - (void)testShouldGetProtectedResource{ client.callbackURL = @"http://someURL.com"; [client validateAuthorizationCode]; - RKTestResponseLoader* resourceLoader = [RKTestResponseLoader responseLoader]; + RKTestResponseLoader *resourceLoader = [RKTestResponseLoader responseLoader]; RKClient *requestClient = [RKClient clientWithBaseURLString:[client authorizationURL]]; requestClient.OAuth2AccessToken = client.accessToken; requestClient.authenticationType = RKRequestAuthenticationTypeOAuth2; diff --git a/Tests/Logic/Network/RKParamsAttachmentTest.m b/Tests/Logic/Network/RKParamsAttachmentTest.m index c2639143b1..bba8f8a78b 100644 --- a/Tests/Logic/Network/RKParamsAttachmentTest.m +++ b/Tests/Logic/Network/RKParamsAttachmentTest.m @@ -29,28 +29,32 @@ @interface RKParamsAttachmentTest : RKTestCase { @implementation RKParamsAttachmentTest -- (void)testShouldRaiseAnExceptionWhenTheAttachedFileDoesNotExist { - NSException* exception = nil; +- (void)testShouldRaiseAnExceptionWhenTheAttachedFileDoesNotExist +{ + NSException *exception = nil; @try { [[RKParamsAttachment alloc] initWithName:@"woot" file:@"/this/is/an/invalid/path"]; } - @catch (NSException* e) { + @catch (NSException *e) { exception = e; } assertThat(exception, isNot(nilValue())); } -- (void)testShouldReturnAnMD5ForSimpleValues { +- (void)testShouldReturnAnMD5ForSimpleValues +{ RKParamsAttachment *attachment = [[[RKParamsAttachment alloc] initWithName:@"foo" value:@"bar"] autorelease]; assertThat([attachment MD5], is(equalTo(@"37b51d194a7513e45b56f6524f2d51f2"))); } -- (void)testShouldReturnAnMD5ForNSData { +- (void)testShouldReturnAnMD5ForNSData +{ RKParamsAttachment *attachment = [[[RKParamsAttachment alloc] initWithName:@"foo" data:[@"bar" dataUsingEncoding:NSUTF8StringEncoding]] autorelease]; assertThat([attachment MD5], is(equalTo(@"37b51d194a7513e45b56f6524f2d51f2"))); } -- (void)testShouldReturnAnMD5ForFiles { +- (void)testShouldReturnAnMD5ForFiles +{ NSString *filePath = [RKTestFixture pathForFixture:@"blake.png"]; RKParamsAttachment *attachment = [[[RKParamsAttachment alloc] initWithName:@"foo" file:filePath] autorelease]; assertThat([attachment MD5], is(equalTo(@"db6cb9d879b58e7e15a595632af345cd"))); diff --git a/Tests/Logic/Network/RKParamsTest.m b/Tests/Logic/Network/RKParamsTest.m index d29699c3bf..e2d3de1d16 100644 --- a/Tests/Logic/Network/RKParamsTest.m +++ b/Tests/Logic/Network/RKParamsTest.m @@ -28,12 +28,13 @@ @interface RKParamsTest : RKTestCase @implementation RKParamsTest -- (void)testShouldNotOverReleaseTheParams { - NSDictionary* dictionary = [NSDictionary dictionaryWithObject:@"foo" forKey:@"bar"]; - RKParams* params = [[RKParams alloc] initWithDictionary:dictionary]; - NSURL* URL = [NSURL URLWithString:[[RKTestFactory baseURLString] stringByAppendingFormat:@"/echo_params"]]; - RKTestResponseLoader* responseLoader = [RKTestResponseLoader responseLoader]; - RKRequest* request = [[RKRequest alloc] initWithURL:URL]; +- (void)testShouldNotOverReleaseTheParams +{ + NSDictionary *dictionary = [NSDictionary dictionaryWithObject:@"foo" forKey:@"bar"]; + RKParams *params = [[RKParams alloc] initWithDictionary:dictionary]; + NSURL *URL = [NSURL URLWithString:[[RKTestFactory baseURLString] stringByAppendingFormat:@"/echo_params"]]; + RKTestResponseLoader *responseLoader = [RKTestResponseLoader responseLoader]; + RKRequest *request = [[RKRequest alloc] initWithURL:URL]; request.method = RKRequestMethodPOST; request.params = params; request.delegate = responseLoader; @@ -42,33 +43,35 @@ - (void)testShouldNotOverReleaseTheParams { [request release]; } -- (void)testShouldUploadFilesViaRKParams { - RKClient* client = [RKTestFactory client]; - RKParams* params = [RKParams params]; +- (void)testShouldUploadFilesViaRKParams +{ + RKClient *client = [RKTestFactory client]; + RKParams *params = [RKParams params]; [params setValue:@"one" forParam:@"value"]; [params setValue:@"two" forParam:@"value"]; [params setValue:@"three" forParam:@"value"]; [params setValue:@"four" forParam:@"value"]; NSData *data = [RKTestFixture dataWithContentsOfFixture:@"blake.png"]; [params setData:data MIMEType:@"image/png" forParam:@"file"]; - RKTestResponseLoader* responseLoader = [RKTestResponseLoader responseLoader]; + RKTestResponseLoader *responseLoader = [RKTestResponseLoader responseLoader]; [client post:@"/upload" params:params delegate:responseLoader]; [responseLoader waitForResponse]; assertThatInteger(responseLoader.response.statusCode, is(equalToInt(200))); } -- (void)testShouldUploadFilesViaRKParamsWithMixedTypes { - NSNumber* idUsuari = [NSNumber numberWithInt:1234]; - NSArray* userList = [NSArray arrayWithObjects:@"one", @"two", @"three", nil]; - NSNumber* idTema = [NSNumber numberWithInt:1234]; - NSString* titulo = @"whatever"; - NSString* texto = @"more text"; +- (void)testShouldUploadFilesViaRKParamsWithMixedTypes +{ + NSNumber *idUsuari = [NSNumber numberWithInt:1234]; + NSArray *userList = [NSArray arrayWithObjects:@"one", @"two", @"three", nil]; + NSNumber *idTema = [NSNumber numberWithInt:1234]; + NSString *titulo = @"whatever"; + NSString *texto = @"more text"; NSData *data = [RKTestFixture dataWithContentsOfFixture:@"blake.png"]; - NSNumber* cel = [NSNumber numberWithFloat:1.232442]; - NSNumber* lon = [NSNumber numberWithFloat:18231.232442];; - NSNumber* lat = [NSNumber numberWithFloat:13213123.232442];; + NSNumber *cel = [NSNumber numberWithFloat:1.232442]; + NSNumber *lon = [NSNumber numberWithFloat:18231.232442];; + NSNumber *lat = [NSNumber numberWithFloat:13213123.232442];; - RKParams* params = [RKParams params]; + RKParams *params = [RKParams params]; // Set values [params setValue:idUsuari forParam:@"idUsuariPropietari"]; @@ -83,23 +86,25 @@ - (void)testShouldUploadFilesViaRKParamsWithMixedTypes { [params setValue:lon forParam:@"lon"]; [params setValue:lat forParam:@"lat"]; - RKClient* client = [RKTestFactory client]; - RKTestResponseLoader* responseLoader = [RKTestResponseLoader responseLoader]; + RKClient *client = [RKTestFactory client]; + RKTestResponseLoader *responseLoader = [RKTestResponseLoader responseLoader]; [client post:@"/upload" params:params delegate:responseLoader]; [responseLoader waitForResponse]; assertThatInteger(responseLoader.response.statusCode, is(equalToInt(200))); } -- (void)testShouldCalculateAnMD5ForTheParams { +- (void)testShouldCalculateAnMD5ForTheParams +{ NSDictionary *values = [NSDictionary dictionaryWithObjectsAndKeys:@"foo", @"bar", @"this", @"that", nil]; RKParams *params = [RKParams paramsWithDictionary:values]; NSString *MD5 = [params MD5]; assertThat(MD5, is(equalTo(@"da7d80084b86aa5022b434e3bf084caf"))); } -- (void)testShouldProperlyCalculateContentLengthForFileUploads { - RKClient* client = [RKTestFactory client]; - RKParams* params = [RKParams params]; +- (void)testShouldProperlyCalculateContentLengthForFileUploads +{ + RKClient *client = [RKTestFactory client]; + RKParams *params = [RKParams params]; [params setValue:@"one" forParam:@"value"]; [params setValue:@"two" forParam:@"value"]; [params setValue:@"three" forParam:@"value"]; diff --git a/Tests/Logic/Network/RKRequestQueueTest.m b/Tests/Logic/Network/RKRequestQueueTest.m index 89c7613f05..65e1182359 100644 --- a/Tests/Logic/Network/RKRequestQueueTest.m +++ b/Tests/Logic/Network/RKRequestQueueTest.m @@ -22,8 +22,8 @@ // Expose the request queue's [add|remove]LoadingRequest methods testing purposes... @interface RKRequestQueue () -- (void)addLoadingRequest:(RKRequest*)request; -- (void)removeLoadingRequest:(RKRequest*)request; +- (void)addLoadingRequest:(RKRequest *)request; +- (void)removeLoadingRequest:(RKRequest *)request; @end @interface RKRequestQueueTest : RKTestCase { @@ -35,16 +35,19 @@ @interface RKRequestQueueTest : RKTestCase { @implementation RKRequestQueueTest -- (void)setUp { +- (void)setUp +{ _autoreleasePool = [NSAutoreleasePool new]; } -- (void)tearDown { +- (void)tearDown +{ [_autoreleasePool drain]; } -- (void)testShouldBeSuspendedWhenInitialized { - RKRequestQueue* queue = [RKRequestQueue new]; +- (void)testShouldBeSuspendedWhenInitialized +{ + RKRequestQueue *queue = [RKRequestQueue new]; assertThatBool(queue.suspended, is(equalToBool(YES))); [queue release]; } @@ -52,9 +55,10 @@ - (void)testShouldBeSuspendedWhenInitialized { #if TARGET_OS_IPHONE // TODO: Crashing... -- (void)testShouldSuspendTheQueueOnTransitionToTheBackground { +- (void)testShouldSuspendTheQueueOnTransitionToTheBackground +{ return; - RKRequestQueue* queue = [RKRequestQueue new]; + RKRequestQueue *queue = [RKRequestQueue new]; assertThatBool(queue.suspended, is(equalToBool(YES))); queue.suspended = NO; [[NSNotificationCenter defaultCenter] postNotificationName:UIApplicationDidEnterBackgroundNotification object:nil]; @@ -62,10 +66,11 @@ - (void)testShouldSuspendTheQueueOnTransitionToTheBackground { [queue release]; } -- (void)testShouldUnsuspendTheQueueOnTransitionToTheForeground { +- (void)testShouldUnsuspendTheQueueOnTransitionToTheForeground +{ // TODO: Crashing... return; - RKRequestQueue* queue = [RKRequestQueue new]; + RKRequestQueue *queue = [RKRequestQueue new]; assertThatBool(queue.suspended, is(equalToBool(YES))); [[NSNotificationCenter defaultCenter] postNotificationName:UIApplicationWillEnterForegroundNotification object:nil]; assertThatBool(queue.suspended, is(equalToBool(NO))); @@ -74,65 +79,70 @@ - (void)testShouldUnsuspendTheQueueOnTransitionToTheForeground { #endif -- (void)testShouldInformTheDelegateWhenSuspended { - RKRequestQueue* queue = [RKRequestQueue new]; +- (void)testShouldInformTheDelegateWhenSuspended +{ + RKRequestQueue *queue = [RKRequestQueue new]; assertThatBool(queue.suspended, is(equalToBool(YES))); queue.suspended = NO; - OCMockObject* delegateMock = [OCMockObject niceMockForProtocol:@protocol(RKRequestQueueDelegate)]; + OCMockObject *delegateMock = [OCMockObject niceMockForProtocol:@protocol(RKRequestQueueDelegate)]; [[delegateMock expect] requestQueueWasSuspended:queue]; - queue.delegate = (NSObject*) delegateMock; + queue.delegate = (NSObject *)delegateMock; queue.suspended = YES; [delegateMock verify]; [queue release]; } -- (void)testShouldInformTheDelegateWhenUnsuspended { - RKRequestQueue* queue = [RKRequestQueue new]; +- (void)testShouldInformTheDelegateWhenUnsuspended +{ + RKRequestQueue *queue = [RKRequestQueue new]; assertThatBool(queue.suspended, is(equalToBool(YES))); - OCMockObject* delegateMock = [OCMockObject niceMockForProtocol:@protocol(RKRequestQueueDelegate)]; + OCMockObject *delegateMock = [OCMockObject niceMockForProtocol:@protocol(RKRequestQueueDelegate)]; [[delegateMock expect] requestQueueWasUnsuspended:queue]; - queue.delegate = (NSObject*) delegateMock; + queue.delegate = (NSObject *)delegateMock; queue.suspended = NO; [delegateMock verify]; [queue release]; } -- (void)testShouldInformTheDelegateOnTransitionFromEmptyToProcessing { - RKRequestQueue* queue = [RKRequestQueue new]; - OCMockObject* delegateMock = [OCMockObject niceMockForProtocol:@protocol(RKRequestQueueDelegate)]; +- (void)testShouldInformTheDelegateOnTransitionFromEmptyToProcessing +{ + RKRequestQueue *queue = [RKRequestQueue new]; + OCMockObject *delegateMock = [OCMockObject niceMockForProtocol:@protocol(RKRequestQueueDelegate)]; [[delegateMock expect] requestQueueDidBeginLoading:queue]; - queue.delegate = (NSObject*) delegateMock; - NSURL* URL = [RKTestFactory baseURL]; - RKRequest* request = [[RKRequest alloc] initWithURL:URL]; + queue.delegate = (NSObject *)delegateMock; + NSURL *URL = [RKTestFactory baseURL]; + RKRequest *request = [[RKRequest alloc] initWithURL:URL]; [queue addLoadingRequest:request]; [delegateMock verify]; [queue release]; } -- (void)testShouldInformTheDelegateOnTransitionFromProcessingToEmpty { - RKRequestQueue* queue = [RKRequestQueue new]; - OCMockObject* delegateMock = [OCMockObject niceMockForProtocol:@protocol(RKRequestQueueDelegate)]; +- (void)testShouldInformTheDelegateOnTransitionFromProcessingToEmpty +{ + RKRequestQueue *queue = [RKRequestQueue new]; + OCMockObject *delegateMock = [OCMockObject niceMockForProtocol:@protocol(RKRequestQueueDelegate)]; [[delegateMock expect] requestQueueDidFinishLoading:queue]; - queue.delegate = (NSObject*) delegateMock; - NSURL* URL = [RKTestFactory baseURL]; - RKRequest* request = [[RKRequest alloc] initWithURL:URL]; + queue.delegate = (NSObject *)delegateMock; + NSURL *URL = [RKTestFactory baseURL]; + RKRequest *request = [[RKRequest alloc] initWithURL:URL]; [queue addLoadingRequest:request]; [queue removeLoadingRequest:request]; [delegateMock verify]; [queue release]; } -- (void)testShouldInformTheDelegateOnTransitionFromProcessingToEmptyForQueuesWithASingleRequest { - OCMockObject* delegateMock = [OCMockObject niceMockForProtocol:@protocol(RKRequestQueueDelegate)]; - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; +- (void)testShouldInformTheDelegateOnTransitionFromProcessingToEmptyForQueuesWithASingleRequest +{ + OCMockObject *delegateMock = [OCMockObject niceMockForProtocol:@protocol(RKRequestQueueDelegate)]; + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - NSString* url = [NSString stringWithFormat:@"%@/ok-with-delay/0.3", [RKTestFactory baseURLString]]; - NSURL* URL = [NSURL URLWithString:url]; - RKRequest * request = [[RKRequest alloc] initWithURL:URL]; + NSString *url = [NSString stringWithFormat:@"%@/ok-with-delay/0.3", [RKTestFactory baseURLString]]; + NSURL *URL = [NSURL URLWithString:url]; + RKRequest *request = [[RKRequest alloc] initWithURL:URL]; request.delegate = loader; - RKRequestQueue* queue = [RKRequestQueue new]; - queue.delegate = (NSObject*) delegateMock; + RKRequestQueue *queue = [RKRequestQueue new]; + queue.delegate = (NSObject *)delegateMock; [[delegateMock expect] requestQueueDidFinishLoading:queue]; [queue addRequest:request]; [queue start]; @@ -145,7 +155,7 @@ - (void)testShouldInformTheDelegateOnTransitionFromProcessingToEmptyForQueuesWit // testing area //- (void)testShouldBeginSpinningTheNetworkActivityIfAsked { // [[UIApplication sharedApplication] rk_resetNetworkActivity]; -// RKRequestQueue* queue = [RKRequestQueue new]; +// RKRequestQueue *queue = [RKRequestQueue new]; // queue.showsNetworkActivityIndicatorWhenBusy = YES; // assertThatBool([UIApplication sharedApplication].networkActivityIndicatorVisible, is(equalToBool(NO))); // [queue setValue:[NSNumber numberWithInt:1] forKey:@"loadingCount"]; @@ -155,7 +165,7 @@ - (void)testShouldInformTheDelegateOnTransitionFromProcessingToEmptyForQueuesWit // //- (void)testShouldStopSpinningTheNetworkActivityIfAsked { // [[UIApplication sharedApplication] rk_resetNetworkActivity]; -// RKRequestQueue* queue = [RKRequestQueue new]; +// RKRequestQueue *queue = [RKRequestQueue new]; // queue.showsNetworkActivityIndicatorWhenBusy = YES; // [queue setValue:[NSNumber numberWithInt:1] forKey:@"loadingCount"]; // assertThatBool([UIApplication sharedApplication].networkActivityIndicatorVisible, is(equalToBool(YES))); @@ -166,21 +176,21 @@ - (void)testShouldInformTheDelegateOnTransitionFromProcessingToEmptyForQueuesWit // //- (void)testShouldJointlyManageTheNetworkActivityIndicator { // [[UIApplication sharedApplication] rk_resetNetworkActivity]; -// RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; +// RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; // loader.timeout = 10; // // RKRequestQueue *queue1 = [RKRequestQueue new]; // queue1.showsNetworkActivityIndicatorWhenBusy = YES; -// NSString* url1 = [NSString stringWithFormat:@"%@/ok-with-delay/2.0", [RKTestFactory baseURL]]; -// NSURL* URL1 = [NSURL URLWithString:url1]; -// RKRequest * request1 = [[RKRequest alloc] initWithURL:URL1]; +// NSString *url1 = [NSString stringWithFormat:@"%@/ok-with-delay/2.0", [RKTestFactory baseURL]]; +// NSURL *URL1 = [NSURL URLWithString:url1]; +// RKRequest *request1 = [[RKRequest alloc] initWithURL:URL1]; // request1.delegate = loader; // // RKRequestQueue *queue2 = [RKRequestQueue new]; // queue2.showsNetworkActivityIndicatorWhenBusy = YES; -// NSString* url2 = [NSString stringWithFormat:@"%@/ok-with-delay/2.0", [RKTestFactory baseURL]]; -// NSURL* URL2 = [NSURL URLWithString:url2]; -// RKRequest * request2 = [[RKRequest alloc] initWithURL:URL2]; +// NSString *url2 = [NSString stringWithFormat:@"%@/ok-with-delay/2.0", [RKTestFactory baseURL]]; +// NSURL *URL2 = [NSURL URLWithString:url2]; +// RKRequest *request2 = [[RKRequest alloc] initWithURL:URL2]; // request2.delegate = loader; // // assertThatBool([UIApplication sharedApplication].networkActivityIndicatorVisible, is(equalToBool(NO))); @@ -196,55 +206,63 @@ - (void)testShouldInformTheDelegateOnTransitionFromProcessingToEmptyForQueuesWit // assertThatBool([UIApplication sharedApplication].networkActivityIndicatorVisible, is(equalToBool(NO))); //} -- (void)testShouldLetYouReturnAQueueByName { - RKRequestQueue* queue = [RKRequestQueue requestQueueWithName:@"Images"]; +- (void)testShouldLetYouReturnAQueueByName +{ + RKRequestQueue *queue = [RKRequestQueue requestQueueWithName:@"Images"]; assertThat(queue, isNot(nilValue())); assertThat(queue.name, is(equalTo(@"Images"))); } -- (void)testShouldReturnAnExistingQueueByName { - RKRequestQueue* queue = [RKRequestQueue requestQueueWithName:@"Images2"]; +- (void)testShouldReturnAnExistingQueueByName +{ + RKRequestQueue *queue = [RKRequestQueue requestQueueWithName:@"Images2"]; assertThat(queue, isNot(nilValue())); - RKRequestQueue* secondQueue = [RKRequestQueue requestQueueWithName:@"Images2"]; + RKRequestQueue *secondQueue = [RKRequestQueue requestQueueWithName:@"Images2"]; assertThat(queue, is(equalTo(secondQueue))); } -- (void)testShouldReturnTheQueueWithoutAModifiedRetainCount { - RKRequestQueue* queue = [RKRequestQueue requestQueueWithName:@"Images3"]; +- (void)testShouldReturnTheQueueWithoutAModifiedRetainCount +{ + RKRequestQueue *queue = [RKRequestQueue requestQueueWithName:@"Images3"]; assertThat(queue, isNot(nilValue())); assertThatUnsignedInteger([queue retainCount], is(equalToInt(1))); } -- (void)testShouldReturnYESWhenAQueueExistsWithAGivenName { +- (void)testShouldReturnYESWhenAQueueExistsWithAGivenName +{ assertThatBool([RKRequestQueue requestQueueExistsWithName:@"Images4"], is(equalToBool(NO))); [RKRequestQueue requestQueueWithName:@"Images4"]; assertThatBool([RKRequestQueue requestQueueExistsWithName:@"Images4"], is(equalToBool(YES))); } -- (void)testShouldRemoveTheQueueFromTheNamedInstancesOnDealloc { +- (void)testShouldRemoveTheQueueFromTheNamedInstancesOnDealloc +{ // TODO: Crashing... return; - RKRequestQueue* queue = [RKRequestQueue requestQueueWithName:@"Images5"]; + RKRequestQueue *queue = [RKRequestQueue requestQueueWithName:@"Images5"]; assertThat(queue, isNot(nilValue())); assertThatBool([RKRequestQueue requestQueueExistsWithName:@"Images5"], is(equalToBool(YES))); [queue release]; assertThatBool([RKRequestQueue requestQueueExistsWithName:@"Images5"], is(equalToBool(NO))); } -- (void)testShouldReturnANewOwningReferenceViaNewRequestWithName { - RKRequestQueue* requestQueue = [RKRequestQueue newRequestQueueWithName:@"Images6"]; +- (void)testShouldReturnANewOwningReferenceViaNewRequestWithName +{ + RKRequestQueue *requestQueue = [RKRequestQueue newRequestQueueWithName:@"Images6"]; assertThat(requestQueue, isNot(nilValue())); assertThatUnsignedInteger([requestQueue retainCount], is(equalToInt(1))); } -- (void)testShouldReturnNilIfNewRequestQueueWithNameIsCalledForAnExistingName { - RKRequestQueue* queue = [RKRequestQueue newRequestQueueWithName:@"Images7"]; +- (void)testShouldReturnNilIfNewRequestQueueWithNameIsCalledForAnExistingName +{ + RKRequestQueue *queue = [RKRequestQueue newRequestQueueWithName:@"Images7"]; assertThat(queue, isNot(nilValue())); - RKRequestQueue* queue2 = [RKRequestQueue newRequestQueueWithName:@"Images7"]; + RKRequestQueue *queue2 = [RKRequestQueue newRequestQueueWithName:@"Images7"]; assertThat(queue2, is(nilValue())); } -- (void)testShouldRemoveItemsFromTheQueueWithAnUnmappableResponse { +- (void)testShouldRemoveItemsFromTheQueueWithAnUnmappableResponse +{ RKRequestQueue *queue = [RKRequestQueue requestQueue]; RKObjectManager *objectManager = [RKTestFactory objectManager]; RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; @@ -256,7 +274,8 @@ - (void)testShouldRemoveItemsFromTheQueueWithAnUnmappableResponse { assertThatUnsignedInteger(queue.loadingCount, is(equalToInt(0))); } -- (void)testThatSendingRequestToInvalidURLDoesNotGetSentTwice { +- (void)testThatSendingRequestToInvalidURLDoesNotGetSentTwice +{ RKRequestQueue *queue = [RKRequestQueue requestQueue]; NSURL *URL = [NSURL URLWithString:@"http://localhost:7662/RKRequestQueueExample"]; RKRequest *request = [RKRequest requestWithURL:URL]; diff --git a/Tests/Logic/Network/RKRequestTest.m b/Tests/Logic/Network/RKRequestTest.m index f039a97ee5..dfa6fadbed 100644 --- a/Tests/Logic/Network/RKRequestTest.m +++ b/Tests/Logic/Network/RKRequestTest.m @@ -38,7 +38,8 @@ @interface RKRequestTest : RKTestCase { @implementation RKRequestTest -- (void)setUp { +- (void)setUp +{ [RKTestFactory setUp]; // Clear the cache directory @@ -46,11 +47,13 @@ - (void)setUp { _methodInvocationCounter = 0; } -- (void)tearDown { +- (void)tearDown +{ [RKTestFactory tearDown]; } -- (int)incrementMethodInvocationCounter { +- (int)incrementMethodInvocationCounter +{ return _methodInvocationCounter++; } @@ -58,49 +61,53 @@ - (int)incrementMethodInvocationCounter { * This spec requires the test Sinatra server to be running * `ruby Tests/server.rb` */ -- (void)testShouldSendMultiPartRequests { - NSString* URLString = [NSString stringWithFormat:@"http://127.0.0.1:4567/photo"]; - NSURL* URL = [NSURL URLWithString:URLString]; - RKRequest* request = [[RKRequest alloc] initWithURL:URL]; - RKParams* params = [[RKParams params] retain]; - NSString* filePath = [RKTestFixture pathForFixture:@"blake.png"]; +- (void)testShouldSendMultiPartRequests +{ + NSString *URLString = [NSString stringWithFormat:@"http://127.0.0.1:4567/photo"]; + NSURL *URL = [NSURL URLWithString:URLString]; + RKRequest *request = [[RKRequest alloc] initWithURL:URL]; + RKParams *params = [[RKParams params] retain]; + NSString *filePath = [RKTestFixture pathForFixture:@"blake.png"]; [params setFile:filePath forParam:@"file"]; [params setValue:@"this is the value" forParam:@"test"]; request.method = RKRequestMethodPOST; request.params = params; - RKResponse* response = [request sendSynchronously]; + RKResponse *response = [request sendSynchronously]; assertThatInteger(response.statusCode, is(equalToInt(200))); } #pragma mark - Basics -- (void)testShouldSetURLRequestHTTPBody { - NSURL* URL = [NSURL URLWithString:[RKTestFactory baseURLString]]; - RKRequest* request = [[RKRequest alloc] initWithURL:URL]; - NSString* JSON = @"whatever"; - NSData* data = [JSON dataUsingEncoding:NSASCIIStringEncoding]; +- (void)testShouldSetURLRequestHTTPBody +{ + NSURL *URL = [NSURL URLWithString:[RKTestFactory baseURLString]]; + RKRequest *request = [[RKRequest alloc] initWithURL:URL]; + NSString *JSON = @"whatever"; + NSData *data = [JSON dataUsingEncoding:NSASCIIStringEncoding]; request.HTTPBody = data; assertThat(request.URLRequest.HTTPBody, equalTo(data)); assertThat(request.HTTPBody, equalTo(data)); assertThat(request.HTTPBodyString, equalTo(JSON)); } -- (void)testShouldSetURLRequestHTTPBodyByString { - NSURL* URL = [NSURL URLWithString:[RKTestFactory baseURLString]]; - RKRequest* request = [[RKRequest alloc] initWithURL:URL]; - NSString* JSON = @"whatever"; - NSData* data = [JSON dataUsingEncoding:NSASCIIStringEncoding]; +- (void)testShouldSetURLRequestHTTPBodyByString +{ + NSURL *URL = [NSURL URLWithString:[RKTestFactory baseURLString]]; + RKRequest *request = [[RKRequest alloc] initWithURL:URL]; + NSString *JSON = @"whatever"; + NSData *data = [JSON dataUsingEncoding:NSASCIIStringEncoding]; request.HTTPBodyString = JSON; assertThat(request.URLRequest.HTTPBody, equalTo(data)); assertThat(request.HTTPBody, equalTo(data)); assertThat(request.HTTPBodyString, equalTo(JSON)); } -- (void)testShouldTimeoutAtIntervalWhenSentAsynchronously { - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; +- (void)testShouldTimeoutAtIntervalWhenSentAsynchronously +{ + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; id loaderMock = [OCMockObject partialMockForObject:loader]; - NSURL* URL = [[RKTestFactory baseURL] URLByAppendingResourcePath:@"/timeout"]; - RKRequest* request = [[RKRequest alloc] initWithURL:URL]; + NSURL *URL = [[RKTestFactory baseURL] URLByAppendingResourcePath:@"/timeout"]; + RKRequest *request = [[RKRequest alloc] initWithURL:URL]; request.delegate = loaderMock; request.timeoutInterval = 3.0; [[[loaderMock expect] andForwardToRealObject] request:request didFailLoadWithError:OCMOCK_ANY]; @@ -110,11 +117,12 @@ - (void)testShouldTimeoutAtIntervalWhenSentAsynchronously { [request release]; } -- (void)testShouldTimeoutAtIntervalWhenSentSynchronously { - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; +- (void)testShouldTimeoutAtIntervalWhenSentSynchronously +{ + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; id loaderMock = [OCMockObject partialMockForObject:loader]; - NSURL* URL = [[RKTestFactory baseURL] URLByAppendingResourcePath:@"/timeout"]; - RKRequest* request = [[RKRequest alloc] initWithURL:URL]; + NSURL *URL = [[RKTestFactory baseURL] URLByAppendingResourcePath:@"/timeout"]; + RKRequest *request = [[RKRequest alloc] initWithURL:URL]; request.delegate = loaderMock; request.timeoutInterval = 3.0; [[[loaderMock expect] andForwardToRealObject] request:request didFailLoadWithError:OCMOCK_ANY]; @@ -123,9 +131,10 @@ - (void)testShouldTimeoutAtIntervalWhenSentSynchronously { [request release]; } -- (void)testShouldCreateOneTimeoutTimerWhenSentAsynchronously { - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; - RKRequest* request = [[RKRequest alloc] initWithURL:[RKTestFactory baseURL]]; +- (void)testShouldCreateOneTimeoutTimerWhenSentAsynchronously +{ + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; + RKRequest *request = [[RKRequest alloc] initWithURL:[RKTestFactory baseURL]]; request.delegate = loader; id requestMock = [OCMockObject partialMockForObject:request]; [[[requestMock expect] andCall:@selector(incrementMethodInvocationCounter) onObject:self] createTimeoutTimer]; @@ -135,11 +144,12 @@ - (void)testShouldCreateOneTimeoutTimerWhenSentAsynchronously { [request release]; } -- (void)testThatSendingDataInvalidatesTimeoutTimer { - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; +- (void)testThatSendingDataInvalidatesTimeoutTimer +{ + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; loader.timeout = 3.0; - NSURL* URL = [[RKTestFactory baseURL] URLByAppendingResourcePath:@"/timeout"]; - RKRequest* request = [[RKRequest alloc] initWithURL:URL]; + NSURL *URL = [[RKTestFactory baseURL] URLByAppendingResourcePath:@"/timeout"]; + RKRequest *request = [[RKRequest alloc] initWithURL:URL]; request.method = RKRequestMethodPOST; request.delegate = loader; request.params = [NSDictionary dictionaryWithObject:@"test" forKey:@"test"]; @@ -150,9 +160,10 @@ - (void)testThatSendingDataInvalidatesTimeoutTimer { [request release]; } -- (void)testThatRunLoopModePropertyRespected { +- (void)testThatRunLoopModePropertyRespected +{ NSString * const dummyRunLoopMode = @"dummyRunLoopMode"; - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; RKRequest *request = [[RKRequest alloc] initWithURL:[RKTestFactory baseURL]]; request.delegate = loader; request.runLoopMode = dummyRunLoopMode; @@ -167,9 +178,10 @@ - (void)testThatRunLoopModePropertyRespected { #if TARGET_OS_IPHONE -- (void)testShouldSendTheRequestWhenBackgroundPolicyIsRKRequestBackgroundPolicyNone { - NSURL* URL = [RKTestFactory baseURL]; - RKRequest* request = [[RKRequest alloc] initWithURL:URL]; +- (void)testShouldSendTheRequestWhenBackgroundPolicyIsRKRequestBackgroundPolicyNone +{ + NSURL *URL = [RKTestFactory baseURL]; + RKRequest *request = [[RKRequest alloc] initWithURL:URL]; request.backgroundPolicy = RKRequestBackgroundPolicyNone; id requestMock = [OCMockObject partialMockForObject:request]; [[requestMock expect] fireAsynchronousRequest]; // Not sure what else to test on this case @@ -177,12 +189,14 @@ - (void)testShouldSendTheRequestWhenBackgroundPolicyIsRKRequestBackgroundPolicyN [requestMock verify]; } -- (UIApplication *)sharedApplicationMock { +- (UIApplication *)sharedApplicationMock +{ id mockApplication = [OCMockObject mockForClass:[UIApplication class]]; return mockApplication; } -- (void)stubSharedApplicationWhileExecutingBlock:(void (^)(void))block { +- (void)stubSharedApplicationWhileExecutingBlock:(void (^)(void))block +{ [self swizzleMethod:@selector(sharedApplication) inClass:[UIApplication class] withMethod:@selector(sharedApplicationMock) @@ -190,10 +204,11 @@ - (void)stubSharedApplicationWhileExecutingBlock:(void (^)(void))block { executeBlock:block]; } -- (void)testShouldObserveForAppBackgroundTransitionsAndCancelTheRequestWhenBackgroundPolicyIsRKRequestBackgroundPolicyCancel { +- (void)testShouldObserveForAppBackgroundTransitionsAndCancelTheRequestWhenBackgroundPolicyIsRKRequestBackgroundPolicyCancel +{ [self stubSharedApplicationWhileExecutingBlock:^{ - NSURL* URL = [RKTestFactory baseURL]; - RKRequest* request = [[RKRequest alloc] initWithURL:URL]; + NSURL *URL = [RKTestFactory baseURL]; + RKRequest *request = [[RKRequest alloc] initWithURL:URL]; request.backgroundPolicy = RKRequestBackgroundPolicyCancel; id requestMock = [OCMockObject partialMockForObject:request]; [[requestMock expect] cancel]; @@ -203,12 +218,13 @@ - (void)testShouldObserveForAppBackgroundTransitionsAndCancelTheRequestWhenBackg }]; } -- (void)testShouldInformTheDelegateOfCancelWhenTheRequestWhenBackgroundPolicyIsRKRequestBackgroundPolicyCancel { +- (void)testShouldInformTheDelegateOfCancelWhenTheRequestWhenBackgroundPolicyIsRKRequestBackgroundPolicyCancel +{ [RKTestFactory client]; [self stubSharedApplicationWhileExecutingBlock:^{ - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; - NSURL* URL = [RKTestFactory baseURL]; - RKRequest* request = [[RKRequest alloc] initWithURL:URL]; + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; + NSURL *URL = [RKTestFactory baseURL]; + RKRequest *request = [[RKRequest alloc] initWithURL:URL]; request.backgroundPolicy = RKRequestBackgroundPolicyCancel; request.delegate = loader; [request sendAsynchronously]; @@ -218,11 +234,12 @@ - (void)testShouldInformTheDelegateOfCancelWhenTheRequestWhenBackgroundPolicyIsR }]; } -- (void)testShouldDeallocTheRequestWhenBackgroundPolicyIsRKRequestBackgroundPolicyCancel { +- (void)testShouldDeallocTheRequestWhenBackgroundPolicyIsRKRequestBackgroundPolicyCancel +{ [RKTestFactory client]; - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; - NSURL* URL = [RKTestFactory baseURL]; - RKRequest* request = [[RKRequest alloc] initWithURL:URL]; + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; + NSURL *URL = [RKTestFactory baseURL]; + RKRequest *request = [[RKRequest alloc] initWithURL:URL]; request.backgroundPolicy = RKRequestBackgroundPolicyCancel; request.delegate = loader; [request sendAsynchronously]; @@ -231,13 +248,14 @@ - (void)testShouldDeallocTheRequestWhenBackgroundPolicyIsRKRequestBackgroundPoli [request release]; } -- (void)testShouldPutTheRequestBackOntoTheQueueWhenBackgroundPolicyIsRKRequestBackgroundPolicyRequeue { +- (void)testShouldPutTheRequestBackOntoTheQueueWhenBackgroundPolicyIsRKRequestBackgroundPolicyRequeue +{ [self stubSharedApplicationWhileExecutingBlock:^{ - RKRequestQueue* queue = [RKRequestQueue new]; + RKRequestQueue *queue = [RKRequestQueue new]; queue.suspended = YES; - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; - NSURL* URL = [RKTestFactory baseURL]; - RKRequest* request = [[RKRequest alloc] initWithURL:URL]; + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; + NSURL *URL = [RKTestFactory baseURL]; + RKRequest *request = [[RKRequest alloc] initWithURL:URL]; request.backgroundPolicy = RKRequestBackgroundPolicyRequeue; request.delegate = loader; request.queue = queue; @@ -249,18 +267,20 @@ - (void)testShouldPutTheRequestBackOntoTheQueueWhenBackgroundPolicyIsRKRequestBa }]; } -- (void)testShouldCreateABackgroundTaskWhenBackgroundPolicyIsRKRequestBackgroundPolicyContinue { - NSURL* URL = [RKTestFactory baseURL]; - RKRequest* request = [[RKRequest alloc] initWithURL:URL]; +- (void)testShouldCreateABackgroundTaskWhenBackgroundPolicyIsRKRequestBackgroundPolicyContinue +{ + NSURL *URL = [RKTestFactory baseURL]; + RKRequest *request = [[RKRequest alloc] initWithURL:URL]; request.backgroundPolicy = RKRequestBackgroundPolicyContinue; [request sendAsynchronously]; assertThatInt(request.backgroundTaskIdentifier, equalToInt(UIBackgroundTaskInvalid)); } -- (void)testShouldSendTheRequestWhenBackgroundPolicyIsNone { - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; - NSURL* URL = [RKTestFactory baseURL]; - RKRequest* request = [[RKRequest alloc] initWithURL:URL]; +- (void)testShouldSendTheRequestWhenBackgroundPolicyIsNone +{ + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; + NSURL *URL = [RKTestFactory baseURL]; + RKRequest *request = [[RKRequest alloc] initWithURL:URL]; request.backgroundPolicy = RKRequestBackgroundPolicyNone; request.delegate = loader; [request sendAsynchronously]; @@ -268,10 +288,11 @@ - (void)testShouldSendTheRequestWhenBackgroundPolicyIsNone { assertThatBool([loader wasSuccessful], is(equalToBool(YES))); } -- (void)testShouldSendTheRequestWhenBackgroundPolicyIsContinue { - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; - NSURL* URL = [RKTestFactory baseURL]; - RKRequest* request = [[RKRequest alloc] initWithURL:URL]; +- (void)testShouldSendTheRequestWhenBackgroundPolicyIsContinue +{ + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; + NSURL *URL = [RKTestFactory baseURL]; + RKRequest *request = [[RKRequest alloc] initWithURL:URL]; request.backgroundPolicy = RKRequestBackgroundPolicyContinue; request.delegate = loader; [request sendAsynchronously]; @@ -279,10 +300,11 @@ - (void)testShouldSendTheRequestWhenBackgroundPolicyIsContinue { assertThatBool([loader wasSuccessful], is(equalToBool(YES))); } -- (void)testShouldSendTheRequestWhenBackgroundPolicyIsCancel { - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; - NSURL* URL = [RKTestFactory baseURL]; - RKRequest* request = [[RKRequest alloc] initWithURL:URL]; +- (void)testShouldSendTheRequestWhenBackgroundPolicyIsCancel +{ + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; + NSURL *URL = [RKTestFactory baseURL]; + RKRequest *request = [[RKRequest alloc] initWithURL:URL]; request.backgroundPolicy = RKRequestBackgroundPolicyCancel; request.delegate = loader; [request sendAsynchronously]; @@ -290,10 +312,11 @@ - (void)testShouldSendTheRequestWhenBackgroundPolicyIsCancel { assertThatBool([loader wasSuccessful], is(equalToBool(YES))); } -- (void)testShouldSendTheRequestWhenBackgroundPolicyIsRequeue { - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; - NSURL* URL = [RKTestFactory baseURL]; - RKRequest* request = [[RKRequest alloc] initWithURL:URL]; +- (void)testShouldSendTheRequestWhenBackgroundPolicyIsRequeue +{ + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; + NSURL *URL = [RKTestFactory baseURL]; + RKRequest *request = [[RKRequest alloc] initWithURL:URL]; request.backgroundPolicy = RKRequestBackgroundPolicyRequeue; request.delegate = loader; [request sendAsynchronously]; @@ -305,11 +328,12 @@ - (void)testShouldSendTheRequestWhenBackgroundPolicyIsRequeue { #pragma mark RKRequestCachePolicy Tests -- (void)testShouldSendTheRequestWhenTheCachePolicyIsNone { - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; - NSString* url = [NSString stringWithFormat:@"%@/etags", [RKTestFactory baseURLString]]; - NSURL* URL = [NSURL URLWithString:url]; - RKRequest* request = [[RKRequest alloc] initWithURL:URL]; +- (void)testShouldSendTheRequestWhenTheCachePolicyIsNone +{ + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; + NSString *url = [NSString stringWithFormat:@"%@/etags", [RKTestFactory baseURLString]]; + NSURL *URL = [NSURL URLWithString:url]; + RKRequest *request = [[RKRequest alloc] initWithURL:URL]; request.cachePolicy = RKRequestCachePolicyNone; request.delegate = loader; [request sendAsynchronously]; @@ -317,45 +341,47 @@ - (void)testShouldSendTheRequestWhenTheCachePolicyIsNone { assertThatBool([loader wasSuccessful], is(equalToBool(YES))); } -- (void)testShouldCacheTheRequestHeadersAndBodyIncludingOurOwnCustomTimestampHeader { - NSString* baseURL = [RKTestFactory baseURLString]; - NSString* cacheDirForClient = [NSString stringWithFormat:@"RKClientRequestCache-%@", +- (void)testShouldCacheTheRequestHeadersAndBodyIncludingOurOwnCustomTimestampHeader +{ + NSString *baseURL = [RKTestFactory baseURLString]; + NSString *cacheDirForClient = [NSString stringWithFormat:@"RKClientRequestCache-%@", [[NSURL URLWithString:baseURL] host]]; - NSString* cachePath = [[RKDirectory cachesDirectory] + NSString *cachePath = [[RKDirectory cachesDirectory] stringByAppendingPathComponent:cacheDirForClient]; - RKRequestCache* cache = [[RKRequestCache alloc] initWithPath:cachePath + RKRequestCache *cache = [[RKRequestCache alloc] initWithPath:cachePath storagePolicy:RKRequestCacheStoragePolicyPermanently]; [cache invalidateWithStoragePolicy:RKRequestCacheStoragePolicyPermanently]; - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; - NSString* url = [NSString stringWithFormat:@"%@/etags/cached", [RKTestFactory baseURLString]]; - NSURL* URL = [NSURL URLWithString:url]; - RKRequest* request = [[RKRequest alloc] initWithURL:URL]; + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; + NSString *url = [NSString stringWithFormat:@"%@/etags/cached", [RKTestFactory baseURLString]]; + NSURL *URL = [NSURL URLWithString:url]; + RKRequest *request = [[RKRequest alloc] initWithURL:URL]; request.cachePolicy = RKRequestCachePolicyEtag; request.cache = cache; request.delegate = loader; [request sendAsynchronously]; [loader waitForResponse]; assertThatBool([loader wasSuccessful], is(equalToBool(YES))); - NSDictionary* headers = [cache headersForRequest:request]; + NSDictionary *headers = [cache headersForRequest:request]; assertThat([headers valueForKey:@"X-RESTKIT-CACHEDATE"], isNot(nilValue())); assertThat([headers valueForKey:@"Etag"], is(equalTo(@"686897696a7c876b7e"))); assertThat([[cache responseForRequest:request] bodyAsString], is(equalTo(@"This Should Get Cached"))); } -- (void)testShouldGenerateAUniqueCacheKeyBasedOnTheUrlTheMethodAndTheHTTPBody { - NSString* baseURL = [RKTestFactory baseURLString]; - NSString* cacheDirForClient = [NSString stringWithFormat:@"RKClientRequestCache-%@", +- (void)testShouldGenerateAUniqueCacheKeyBasedOnTheUrlTheMethodAndTheHTTPBody +{ + NSString *baseURL = [RKTestFactory baseURLString]; + NSString *cacheDirForClient = [NSString stringWithFormat:@"RKClientRequestCache-%@", [[NSURL URLWithString:baseURL] host]]; - NSString* cachePath = [[RKDirectory cachesDirectory] + NSString *cachePath = [[RKDirectory cachesDirectory] stringByAppendingPathComponent:cacheDirForClient]; - RKRequestCache* cache = [[RKRequestCache alloc] initWithPath:cachePath + RKRequestCache *cache = [[RKRequestCache alloc] initWithPath:cachePath storagePolicy:RKRequestCacheStoragePolicyPermanently]; [cache invalidateWithStoragePolicy:RKRequestCacheStoragePolicyPermanently]; - NSString* url = [NSString stringWithFormat:@"%@/etags/cached", [RKTestFactory baseURLString]]; - NSURL* URL = [NSURL URLWithString:url]; - RKRequest* request = [[RKRequest alloc] initWithURL:URL]; + NSString *url = [NSString stringWithFormat:@"%@/etags/cached", [RKTestFactory baseURLString]]; + NSURL *URL = [NSURL URLWithString:url]; + RKRequest *request = [[RKRequest alloc] initWithURL:URL]; request.cachePolicy = RKRequestCachePolicyEtag; request.method = RKRequestMethodDELETE; // Don't cache delete. cache key should be nil. @@ -368,20 +394,21 @@ - (void)testShouldGenerateAUniqueCacheKeyBasedOnTheUrlTheMethodAndTheHTTPBody { assertThat([request cacheKey], is(nilValue())); } -- (void)testShouldLoadFromCacheWhenWeRecieveA304 { - NSString* baseURL = [RKTestFactory baseURLString]; - NSString* cacheDirForClient = [NSString stringWithFormat:@"RKClientRequestCache-%@", +- (void)testShouldLoadFromCacheWhenWeRecieveA304 +{ + NSString *baseURL = [RKTestFactory baseURLString]; + NSString *cacheDirForClient = [NSString stringWithFormat:@"RKClientRequestCache-%@", [[NSURL URLWithString:baseURL] host]]; - NSString* cachePath = [[RKDirectory cachesDirectory] + NSString *cachePath = [[RKDirectory cachesDirectory] stringByAppendingPathComponent:cacheDirForClient]; - RKRequestCache* cache = [[RKRequestCache alloc] initWithPath:cachePath + RKRequestCache *cache = [[RKRequestCache alloc] initWithPath:cachePath storagePolicy:RKRequestCacheStoragePolicyPermanently]; [cache invalidateWithStoragePolicy:RKRequestCacheStoragePolicyPermanently]; { - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; - NSString* url = [NSString stringWithFormat:@"%@/etags/cached", [RKTestFactory baseURLString]]; - NSURL* URL = [NSURL URLWithString:url]; - RKRequest* request = [[RKRequest alloc] initWithURL:URL]; + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; + NSString *url = [NSString stringWithFormat:@"%@/etags/cached", [RKTestFactory baseURLString]]; + NSURL *URL = [NSURL URLWithString:url]; + RKRequest *request = [[RKRequest alloc] initWithURL:URL]; request.cachePolicy = RKRequestCachePolicyEtag; request.cache = cache; request.delegate = loader; @@ -393,10 +420,10 @@ - (void)testShouldLoadFromCacheWhenWeRecieveA304 { assertThatBool([loader.response wasLoadedFromCache], is(equalToBool(NO))); } { - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; - NSString* url = [NSString stringWithFormat:@"%@/etags/cached", [RKTestFactory baseURLString]]; - NSURL* URL = [NSURL URLWithString:url]; - RKRequest* request = [[RKRequest alloc] initWithURL:URL]; + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; + NSString *url = [NSString stringWithFormat:@"%@/etags/cached", [RKTestFactory baseURLString]]; + NSURL *URL = [NSURL URLWithString:url]; + RKRequest *request = [[RKRequest alloc] initWithURL:URL]; request.cachePolicy = RKRequestCachePolicyEtag; request.cache = cache; request.delegate = loader; @@ -408,23 +435,24 @@ - (void)testShouldLoadFromCacheWhenWeRecieveA304 { } } -- (void)testShouldUpdateTheInternalCacheDateWhenWeRecieveA304 { - NSString* baseURL = [RKTestFactory baseURLString]; - NSString* cacheDirForClient = [NSString stringWithFormat:@"RKClientRequestCache-%@", +- (void)testShouldUpdateTheInternalCacheDateWhenWeRecieveA304 +{ + NSString *baseURL = [RKTestFactory baseURLString]; + NSString *cacheDirForClient = [NSString stringWithFormat:@"RKClientRequestCache-%@", [[NSURL URLWithString:baseURL] host]]; - NSString* cachePath = [[RKDirectory cachesDirectory] + NSString *cachePath = [[RKDirectory cachesDirectory] stringByAppendingPathComponent:cacheDirForClient]; - RKRequestCache* cache = [[RKRequestCache alloc] initWithPath:cachePath + RKRequestCache *cache = [[RKRequestCache alloc] initWithPath:cachePath storagePolicy:RKRequestCacheStoragePolicyPermanently]; [cache invalidateWithStoragePolicy:RKRequestCacheStoragePolicyPermanently]; - NSDate* internalCacheDate1; - NSDate* internalCacheDate2; + NSDate *internalCacheDate1; + NSDate *internalCacheDate2; { - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; - NSString* url = [NSString stringWithFormat:@"%@/etags/cached", [RKTestFactory baseURLString]]; - NSURL* URL = [NSURL URLWithString:url]; - RKRequest* request = [[RKRequest alloc] initWithURL:URL]; + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; + NSString *url = [NSString stringWithFormat:@"%@/etags/cached", [RKTestFactory baseURLString]]; + NSURL *URL = [NSURL URLWithString:url]; + RKRequest *request = [[RKRequest alloc] initWithURL:URL]; request.cachePolicy = RKRequestCachePolicyEtag; request.cache = cache; request.delegate = loader; @@ -438,10 +466,10 @@ - (void)testShouldUpdateTheInternalCacheDateWhenWeRecieveA304 { } [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1.5]]; { - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; - NSString* url = [NSString stringWithFormat:@"%@/etags/cached", [RKTestFactory baseURLString]]; - NSURL* URL = [NSURL URLWithString:url]; - RKRequest* request = [[RKRequest alloc] initWithURL:URL]; + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; + NSString *url = [NSString stringWithFormat:@"%@/etags/cached", [RKTestFactory baseURLString]]; + NSURL *URL = [NSURL URLWithString:url]; + RKRequest *request = [[RKRequest alloc] initWithURL:URL]; request.cachePolicy = RKRequestCachePolicyEtag; request.cache = cache; request.delegate = loader; @@ -455,21 +483,22 @@ - (void)testShouldUpdateTheInternalCacheDateWhenWeRecieveA304 { assertThat(internalCacheDate1, isNot(internalCacheDate2)); } -- (void)testShouldLoadFromTheCacheIfThereIsAnError { - NSString* baseURL = [RKTestFactory baseURLString]; - NSString* cacheDirForClient = [NSString stringWithFormat:@"RKClientRequestCache-%@", +- (void)testShouldLoadFromTheCacheIfThereIsAnError +{ + NSString *baseURL = [RKTestFactory baseURLString]; + NSString *cacheDirForClient = [NSString stringWithFormat:@"RKClientRequestCache-%@", [[NSURL URLWithString:baseURL] host]]; - NSString* cachePath = [[RKDirectory cachesDirectory] + NSString *cachePath = [[RKDirectory cachesDirectory] stringByAppendingPathComponent:cacheDirForClient]; - RKRequestCache* cache = [[RKRequestCache alloc] initWithPath:cachePath + RKRequestCache *cache = [[RKRequestCache alloc] initWithPath:cachePath storagePolicy:RKRequestCacheStoragePolicyPermanently]; [cache invalidateWithStoragePolicy:RKRequestCacheStoragePolicyPermanently]; { - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; - NSString* url = [NSString stringWithFormat:@"%@/etags/cached", [RKTestFactory baseURLString]]; - NSURL* URL = [NSURL URLWithString:url]; - RKRequest* request = [[RKRequest alloc] initWithURL:URL]; + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; + NSString *url = [NSString stringWithFormat:@"%@/etags/cached", [RKTestFactory baseURLString]]; + NSURL *URL = [NSURL URLWithString:url]; + RKRequest *request = [[RKRequest alloc] initWithURL:URL]; request.cachePolicy = RKRequestCachePolicyEtag; request.cache = cache; request.delegate = loader; @@ -480,10 +509,10 @@ - (void)testShouldLoadFromTheCacheIfThereIsAnError { assertThatBool([loader.response wasLoadedFromCache], is(equalToBool(NO))); } { - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; - NSString* url = [NSString stringWithFormat:@"%@/etags/cached", [RKTestFactory baseURLString]]; - NSURL* URL = [NSURL URLWithString:url]; - RKRequest* request = [[RKRequest alloc] initWithURL:URL]; + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; + NSString *url = [NSString stringWithFormat:@"%@/etags/cached", [RKTestFactory baseURLString]]; + NSURL *URL = [NSURL URLWithString:url]; + RKRequest *request = [[RKRequest alloc] initWithURL:URL]; request.cachePolicy = RKRequestCachePolicyLoadOnError; request.cache = cache; request.delegate = loader; @@ -493,21 +522,22 @@ - (void)testShouldLoadFromTheCacheIfThereIsAnError { } } -- (void)testShouldLoadFromTheCacheIfWeAreWithinTheTimeout { - NSString* baseURL = [RKTestFactory baseURLString]; - NSString* cacheDirForClient = [NSString stringWithFormat:@"RKClientRequestCache-%@", +- (void)testShouldLoadFromTheCacheIfWeAreWithinTheTimeout +{ + NSString *baseURL = [RKTestFactory baseURLString]; + NSString *cacheDirForClient = [NSString stringWithFormat:@"RKClientRequestCache-%@", [[NSURL URLWithString:baseURL] host]]; - NSString* cachePath = [[RKDirectory cachesDirectory] + NSString *cachePath = [[RKDirectory cachesDirectory] stringByAppendingPathComponent:cacheDirForClient]; - RKRequestCache* cache = [[RKRequestCache alloc] initWithPath:cachePath + RKRequestCache *cache = [[RKRequestCache alloc] initWithPath:cachePath storagePolicy:RKRequestCacheStoragePolicyPermanently]; [cache invalidateWithStoragePolicy:RKRequestCacheStoragePolicyPermanently]; - NSString* url = [NSString stringWithFormat:@"%@/disk/cached", [RKTestFactory baseURLString]]; - NSURL* URL = [NSURL URLWithString:url]; + NSString *url = [NSString stringWithFormat:@"%@/disk/cached", [RKTestFactory baseURLString]]; + NSURL *URL = [NSURL URLWithString:url]; { - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; - RKRequest* request = [[RKRequest alloc] initWithURL:URL]; + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; + RKRequest *request = [[RKRequest alloc] initWithURL:URL]; request.cachePolicy = RKRequestCachePolicyTimeout; request.cacheTimeoutInterval = 5; request.cache = cache; @@ -519,8 +549,8 @@ - (void)testShouldLoadFromTheCacheIfWeAreWithinTheTimeout { assertThatBool([loader.response wasLoadedFromCache], is(equalToBool(NO))); } { - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; - RKRequest* request = [[RKRequest alloc] initWithURL:URL]; + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; + RKRequest *request = [[RKRequest alloc] initWithURL:URL]; request.cachePolicy = RKRequestCachePolicyTimeout; request.cacheTimeoutInterval = 5; request.cache = cache; @@ -531,8 +561,8 @@ - (void)testShouldLoadFromTheCacheIfWeAreWithinTheTimeout { assertThatBool([loader.response wasLoadedFromCache], is(equalToBool(YES))); } { - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; - RKRequest* request = [[RKRequest alloc] initWithURL:URL]; + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; + RKRequest *request = [[RKRequest alloc] initWithURL:URL]; request.cachePolicy = RKRequestCachePolicyTimeout; request.cacheTimeoutInterval = 5; request.cache = cache; @@ -543,8 +573,8 @@ - (void)testShouldLoadFromTheCacheIfWeAreWithinTheTimeout { assertThatBool([loader.response wasLoadedFromCache], is(equalToBool(YES))); } { - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; - RKRequest* request = [[RKRequest alloc] initWithURL:URL]; + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; + RKRequest *request = [[RKRequest alloc] initWithURL:URL]; request.cachePolicy = RKRequestCachePolicyTimeout; request.cacheTimeoutInterval = 0; request.cache = cache; @@ -557,22 +587,23 @@ - (void)testShouldLoadFromTheCacheIfWeAreWithinTheTimeout { } } -- (void)testShouldLoadFromTheCacheIfWeAreOffline { - NSString* baseURL = [RKTestFactory baseURLString]; - NSString* cacheDirForClient = [NSString stringWithFormat:@"RKClientRequestCache-%@", +- (void)testShouldLoadFromTheCacheIfWeAreOffline +{ + NSString *baseURL = [RKTestFactory baseURLString]; + NSString *cacheDirForClient = [NSString stringWithFormat:@"RKClientRequestCache-%@", [[NSURL URLWithString:baseURL] host]]; - NSString* cachePath = [[RKDirectory cachesDirectory] + NSString *cachePath = [[RKDirectory cachesDirectory] stringByAppendingPathComponent:cacheDirForClient]; - RKRequestCache* cache = [[RKRequestCache alloc] initWithPath:cachePath + RKRequestCache *cache = [[RKRequestCache alloc] initWithPath:cachePath storagePolicy:RKRequestCacheStoragePolicyPermanently]; [cache invalidateWithStoragePolicy:RKRequestCacheStoragePolicyPermanently]; { - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; loader.timeout = 60; - NSString* url = [NSString stringWithFormat:@"%@/etags/cached", [RKTestFactory baseURLString]]; - NSURL* URL = [NSURL URLWithString:url]; - RKRequest* request = [[RKRequest alloc] initWithURL:URL]; + NSString *url = [NSString stringWithFormat:@"%@/etags/cached", [RKTestFactory baseURLString]]; + NSURL *URL = [NSURL URLWithString:url]; + RKRequest *request = [[RKRequest alloc] initWithURL:URL]; request.cachePolicy = RKRequestCachePolicyEtag; request.cache = cache; request.delegate = loader; @@ -583,11 +614,11 @@ - (void)testShouldLoadFromTheCacheIfWeAreOffline { assertThatBool([loader.response wasLoadedFromCache], is(equalToBool(NO))); } { - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; loader.timeout = 60; - NSString* url = [NSString stringWithFormat:@"%@/etags/cached", [RKTestFactory baseURLString]]; - NSURL* URL = [NSURL URLWithString:url]; - RKRequest* request = [[RKRequest alloc] initWithURL:URL]; + NSString *url = [NSString stringWithFormat:@"%@/etags/cached", [RKTestFactory baseURLString]]; + NSURL *URL = [NSURL URLWithString:url]; + RKRequest *request = [[RKRequest alloc] initWithURL:URL]; request.cachePolicy = RKRequestCachePolicyLoadIfOffline; request.cache = cache; request.delegate = loader; @@ -600,21 +631,22 @@ - (void)testShouldLoadFromTheCacheIfWeAreOffline { } } -- (void)testShouldCacheTheStatusCodeMIMETypeAndURL { - NSString* baseURL = [RKTestFactory baseURLString]; - NSString* cacheDirForClient = [NSString stringWithFormat:@"RKClientRequestCache-%@", +- (void)testShouldCacheTheStatusCodeMIMETypeAndURL +{ + NSString *baseURL = [RKTestFactory baseURLString]; + NSString *cacheDirForClient = [NSString stringWithFormat:@"RKClientRequestCache-%@", [[NSURL URLWithString:baseURL] host]]; - NSString* cachePath = [[RKDirectory cachesDirectory] + NSString *cachePath = [[RKDirectory cachesDirectory] stringByAppendingPathComponent:cacheDirForClient]; - RKRequestCache* cache = [[RKRequestCache alloc] initWithPath:cachePath + RKRequestCache *cache = [[RKRequestCache alloc] initWithPath:cachePath storagePolicy:RKRequestCacheStoragePolicyPermanently]; [cache invalidateWithStoragePolicy:RKRequestCacheStoragePolicyPermanently]; { - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; - NSString* url = [NSString stringWithFormat:@"%@/etags/cached", [RKTestFactory baseURLString]]; - NSURL* URL = [NSURL URLWithString:url]; - RKRequest* request = [[RKRequest alloc] initWithURL:URL]; + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; + NSString *url = [NSString stringWithFormat:@"%@/etags/cached", [RKTestFactory baseURLString]]; + NSURL *URL = [NSURL URLWithString:url]; + RKRequest *request = [[RKRequest alloc] initWithURL:URL]; request.cachePolicy = RKRequestCachePolicyEtag; request.cache = cache; request.delegate = loader; @@ -627,10 +659,10 @@ - (void)testShouldCacheTheStatusCodeMIMETypeAndURL { assertThatBool([loader.response wasLoadedFromCache], is(equalToBool(NO))); } { - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; - NSString* url = [NSString stringWithFormat:@"%@/etags/cached", [RKTestFactory baseURLString]]; - NSURL* URL = [NSURL URLWithString:url]; - RKRequest* request = [[RKRequest alloc] initWithURL:URL]; + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; + NSString *url = [NSString stringWithFormat:@"%@/etags/cached", [RKTestFactory baseURLString]]; + NSURL *URL = [NSURL URLWithString:url]; + RKRequest *request = [[RKRequest alloc] initWithURL:URL]; request.cachePolicy = RKRequestCachePolicyEtag; request.cache = cache; request.delegate = loader; @@ -644,74 +676,81 @@ - (void)testShouldCacheTheStatusCodeMIMETypeAndURL { } } -- (void)testShouldPostSimpleKeyValuesViaRKParams { - RKParams* params = [RKParams params]; +- (void)testShouldPostSimpleKeyValuesViaRKParams +{ + RKParams *params = [RKParams params]; - [params setValue: @"hello" forParam:@"username"]; - [params setValue: @"password" forParam:@"password"]; + [params setValue:@"hello" forParam:@"username"]; + [params setValue:@"password" forParam:@"password"]; - RKClient* client = [RKTestFactory client]; + RKClient *client = [RKTestFactory client]; client.cachePolicy = RKRequestCachePolicyNone; - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; loader.timeout = 20; [client post:@"/echo_params" params:params delegate:loader]; [loader waitForResponse]; assertThat([loader.response bodyAsString], is(equalTo(@"{\"username\":\"hello\",\"password\":\"password\"}"))); } -- (void)testShouldSetAnEmptyContentBodyWhenParamsIsNil { - RKClient* client = [RKTestFactory client]; +- (void)testShouldSetAnEmptyContentBodyWhenParamsIsNil +{ + RKClient *client = [RKTestFactory client]; client.cachePolicy = RKRequestCachePolicyNone; - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; loader.timeout = 20; - RKRequest* request = [client get:@"/echo_params" delegate:loader]; + RKRequest *request = [client get:@"/echo_params" delegate:loader]; [loader waitForResponse]; assertThat([request.URLRequest valueForHTTPHeaderField:@"Content-Length"], is(equalTo(@"0"))); } -- (void)testShouldSetAnEmptyContentBodyWhenQueryParamsIsAnEmptyDictionary { - RKClient* client = [RKTestFactory client]; +- (void)testShouldSetAnEmptyContentBodyWhenQueryParamsIsAnEmptyDictionary +{ + RKClient *client = [RKTestFactory client]; client.cachePolicy = RKRequestCachePolicyNone; - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; loader.timeout = 20; - RKRequest* request = [client get:@"/echo_params" queryParameters:[NSDictionary dictionary] delegate:loader]; + RKRequest *request = [client get:@"/echo_params" queryParameters:[NSDictionary dictionary] delegate:loader]; [loader waitForResponse]; assertThat([request.URLRequest valueForHTTPHeaderField:@"Content-Length"], is(equalTo(@"0"))); } -- (void)testShouldPUTWithParams { - RKClient* client = [RKTestFactory client]; +- (void)testShouldPUTWithParams +{ + RKClient *client = [RKTestFactory client]; RKParams *params = [RKParams params]; [params setValue:@"ddss" forParam:@"username"]; [params setValue:@"aaaa@aa.com" forParam:@"email"]; - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; [client put:@"/ping" params:params delegate:loader]; [loader waitForResponse]; assertThat([loader.response bodyAsString], is(equalTo(@"{\"username\":\"ddss\",\"email\":\"aaaa@aa.com\"}"))); } -- (void)testShouldAllowYouToChangeTheURL { - NSURL* URL = [NSURL URLWithString:@"http://restkit.org/monkey"]; - RKRequest* request = [RKRequest requestWithURL:URL]; +- (void)testShouldAllowYouToChangeTheURL +{ + NSURL *URL = [NSURL URLWithString:@"http://restkit.org/monkey"]; + RKRequest *request = [RKRequest requestWithURL:URL]; request.URL = [NSURL URLWithString:@"http://restkit.org/gorilla"]; assertThat([request.URL absoluteString], is(equalTo(@"http://restkit.org/gorilla"))); } -- (void)testShouldAllowYouToChangeTheResourcePath { - RKURL* URL = [[RKURL URLWithString:@"http://restkit.org"] URLByAppendingResourcePath:@"/monkey"]; - RKRequest* request = [RKRequest requestWithURL:URL]; +- (void)testShouldAllowYouToChangeTheResourcePath +{ + RKURL *URL = [[RKURL URLWithString:@"http://restkit.org"] URLByAppendingResourcePath:@"/monkey"]; + RKRequest *request = [RKRequest requestWithURL:URL]; request.resourcePath = @"/gorilla"; assertThat(request.resourcePath, is(equalTo(@"/gorilla"))); } -- (void)testShouldNotRaiseAnExceptionWhenAttemptingToMutateResourcePathOnAnNSURL { - NSURL* URL = [NSURL URLWithString:@"http://restkit.org/monkey"]; - RKRequest* request = [RKRequest requestWithURL:URL]; - NSException* exception = nil; +- (void)testShouldNotRaiseAnExceptionWhenAttemptingToMutateResourcePathOnAnNSURL +{ + NSURL *URL = [NSURL URLWithString:@"http://restkit.org/monkey"]; + RKRequest *request = [RKRequest requestWithURL:URL]; + NSException *exception = nil; @try { request.resourcePath = @"/gorilla"; } - @catch (NSException* e) { + @catch (NSException *e) { exception = e; } @finally { @@ -719,7 +758,8 @@ - (void)testShouldNotRaiseAnExceptionWhenAttemptingToMutateResourcePathOnAnNSURL } } -- (void)testShouldOptionallySkipSSLValidation { +- (void)testShouldOptionallySkipSSLValidation +{ NSURL *URL = [NSURL URLWithString:@"https://blakewatters.com/"]; RKRequest *request = [RKRequest requestWithURL:URL]; request.disableCertificateValidation = YES; @@ -727,12 +767,13 @@ - (void)testShouldOptionallySkipSSLValidation { assertThatBool([response isOK], is(equalToBool(YES))); } -- (void)testShouldNotAddANonZeroContentLengthHeaderIfParamsIsSetAndThisIsAGETRequest { - RKClient* client = [RKTestFactory client]; +- (void)testShouldNotAddANonZeroContentLengthHeaderIfParamsIsSetAndThisIsAGETRequest +{ + RKClient *client = [RKTestFactory client]; client.disableCertificateValidation = YES; - NSURL* URL = [NSURL URLWithString:@"https://blakewatters.com/"]; - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; - RKRequest* request = [RKRequest requestWithURL:URL]; + NSURL *URL = [NSURL URLWithString:@"https://blakewatters.com/"]; + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; + RKRequest *request = [RKRequest requestWithURL:URL]; request.delegate = loader; request.params = [NSDictionary dictionaryWithObject:@"foo" forKey:@"bar"]; [request send]; @@ -740,12 +781,13 @@ - (void)testShouldNotAddANonZeroContentLengthHeaderIfParamsIsSetAndThisIsAGETReq assertThat([request.URLRequest valueForHTTPHeaderField:@"Content-Length"], is(equalTo(@"0"))); } -- (void)testShouldNotAddANonZeroContentLengthHeaderIfParamsIsSetAndThisIsAHEADRequest { - RKClient* client = [RKTestFactory client]; +- (void)testShouldNotAddANonZeroContentLengthHeaderIfParamsIsSetAndThisIsAHEADRequest +{ + RKClient *client = [RKTestFactory client]; client.disableCertificateValidation = YES; - NSURL* URL = [NSURL URLWithString:@"https://blakewatters.com/"]; - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; - RKRequest* request = [RKRequest requestWithURL:URL]; + NSURL *URL = [NSURL URLWithString:@"https://blakewatters.com/"]; + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; + RKRequest *request = [RKRequest requestWithURL:URL]; request.delegate = loader; request.method = RKRequestMethodHEAD; request.params = [NSDictionary dictionaryWithObject:@"foo" forKey:@"bar"]; @@ -754,7 +796,8 @@ - (void)testShouldNotAddANonZeroContentLengthHeaderIfParamsIsSetAndThisIsAHEADRe assertThat([request.URLRequest valueForHTTPHeaderField:@"Content-Length"], is(equalTo(@"0"))); } -- (void)testShouldLetYouHandleResponsesWithABlock { +- (void)testShouldLetYouHandleResponsesWithABlock +{ RKURL *URL = [[RKTestFactory baseURL] URLByAppendingResourcePath:@"/ping"]; RKRequest *request = [RKRequest requestWithURL:URL]; RKTestResponseLoader *responseLoader = [RKTestResponseLoader responseLoader]; @@ -768,7 +811,8 @@ - (void)testShouldLetYouHandleResponsesWithABlock { assertThatBool(blockInvoked, is(equalToBool(YES))); } -- (void)testShouldLetYouHandleErrorsWithABlock { +- (void)testShouldLetYouHandleErrorsWithABlock +{ RKURL *URL = [[RKTestFactory baseURL] URLByAppendingResourcePath:@"/fail"]; RKRequest *request = [RKRequest requestWithURL:URL]; RKTestResponseLoader *responseLoader = [RKTestResponseLoader responseLoader]; @@ -783,16 +827,17 @@ - (void)testShouldLetYouHandleErrorsWithABlock { } // TODO: Move to RKRequestCacheTest -- (void)testShouldReturnACachePathWhenTheRequestIsUsingRKParams { +- (void)testShouldReturnACachePathWhenTheRequestIsUsingRKParams +{ RKParams *params = [RKParams params]; [params setValue:@"foo" forParam:@"bar"]; NSURL *URL = [NSURL URLWithString:@"http://restkit.org/"]; RKRequest *request = [RKRequest requestWithURL:URL]; request.params = params; - NSString* baseURL = [RKTestFactory baseURLString]; - NSString* cacheDirForClient = [NSString stringWithFormat:@"RKClientRequestCache-%@", + NSString *baseURL = [RKTestFactory baseURLString]; + NSString *cacheDirForClient = [NSString stringWithFormat:@"RKClientRequestCache-%@", [[NSURL URLWithString:baseURL] host]]; - NSString* cachePath = [[RKDirectory cachesDirectory] + NSString *cachePath = [[RKDirectory cachesDirectory] stringByAppendingPathComponent:cacheDirForClient]; RKRequestCache *requestCache = [[RKRequestCache alloc] initWithPath:cachePath storagePolicy:RKRequestCacheStoragePolicyForDurationOfSession]; NSString *requestCachePath = [requestCache pathForRequest:request]; @@ -801,23 +846,25 @@ - (void)testShouldReturnACachePathWhenTheRequestIsUsingRKParams { assertThat(cacheFile, is(equalTo(@"SessionStore/4ba47367884760141da2e38fda525a1f"))); } -- (void)testShouldReturnNilForCachePathWhenTheRequestIsADELETE { +- (void)testShouldReturnNilForCachePathWhenTheRequestIsADELETE +{ RKParams *params = [RKParams params]; [params setValue:@"foo" forParam:@"bar"]; NSURL *URL = [NSURL URLWithString:@"http://restkit.org/"]; RKRequest *request = [RKRequest requestWithURL:URL]; request.method = RKRequestMethodDELETE; - NSString* baseURL = [RKTestFactory baseURLString]; - NSString* cacheDirForClient = [NSString stringWithFormat:@"RKClientRequestCache-%@", + NSString *baseURL = [RKTestFactory baseURLString]; + NSString *cacheDirForClient = [NSString stringWithFormat:@"RKClientRequestCache-%@", [[NSURL URLWithString:baseURL] host]]; - NSString* cachePath = [[RKDirectory cachesDirectory] + NSString *cachePath = [[RKDirectory cachesDirectory] stringByAppendingPathComponent:cacheDirForClient]; RKRequestCache *requestCache = [[RKRequestCache alloc] initWithPath:cachePath storagePolicy:RKRequestCacheStoragePolicyForDurationOfSession]; NSString *requestCachePath = [requestCache pathForRequest:request]; assertThat(requestCachePath, is(nilValue())); } -- (void)testShouldBuildAProperAuthorizationHeaderForOAuth1 { +- (void)testShouldBuildAProperAuthorizationHeaderForOAuth1 +{ RKRequest *request = [RKRequest requestWithURL:[RKURL URLWithString:@"http://restkit.org/this?that=foo&bar=word"]]; request.authenticationType = RKRequestAuthenticationTypeOAuth1; request.OAuth1AccessToken = @"12345"; @@ -829,7 +876,8 @@ - (void)testShouldBuildAProperAuthorizationHeaderForOAuth1 { assertThat(authorization, isNot(nilValue())); } -- (void)testShouldBuildAProperAuthorizationHeaderForOAuth1ThatIsAcceptedByServer { +- (void)testShouldBuildAProperAuthorizationHeaderForOAuth1ThatIsAcceptedByServer +{ RKRequest *request = [RKRequest requestWithURL:[RKURL URLWithString:[NSString stringWithFormat:@"%@/oauth1/me", [RKTestFactory baseURLString]]]]; request.authenticationType = RKRequestAuthenticationTypeOAuth1; request.OAuth1AccessToken = @"12345"; @@ -847,7 +895,8 @@ - (void)testShouldBuildAProperAuthorizationHeaderForOAuth1ThatIsAcceptedByServer assertThatBool(responseLoader.successful, is(equalToBool(YES))); } -- (void)testImproperOAuth1CredentialsShouldFall { +- (void)testImproperOAuth1CredentialsShouldFall +{ RKRequest *request = [RKRequest requestWithURL:[RKURL URLWithString:[NSString stringWithFormat:@"%@/oauth1/me", [RKTestFactory baseURLString]]]]; request.authenticationType = RKRequestAuthenticationTypeOAuth1; request.OAuth1AccessToken = @"12345"; @@ -865,9 +914,10 @@ - (void)testImproperOAuth1CredentialsShouldFall { assertThatBool(responseLoader.successful, is(equalToBool(YES))); } -- (void)testOnDidLoadResponseBlockInvocation { +- (void)testOnDidLoadResponseBlockInvocation +{ RKURL *URL = [[RKTestFactory baseURL] URLByAppendingResourcePath:@"/200"]; - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; RKRequest *request = [RKRequest requestWithURL:URL]; __block RKResponse *blockResponse = nil; request.onDidLoadResponse = ^ (RKResponse *response) { @@ -879,7 +929,8 @@ - (void)testOnDidLoadResponseBlockInvocation { assertThat(blockResponse, is(notNilValue())); } -- (void)testOnDidFailLoadWithErrorBlockInvocation { +- (void)testOnDidFailLoadWithErrorBlockInvocation +{ RKURL *URL = [[RKTestFactory baseURL] URLByAppendingResourcePath:@"/503"]; RKRequest *request = [RKRequest requestWithURL:URL]; __block NSError *blockError = nil; @@ -891,8 +942,9 @@ - (void)testOnDidFailLoadWithErrorBlockInvocation { assertThat(blockError, is(notNilValue())); } -- (void)testShouldBuildAProperRequestWhenSettingBodyByMIMEType { - RKClient* client = [RKTestFactory client]; +- (void)testShouldBuildAProperRequestWhenSettingBodyByMIMEType +{ + RKClient *client = [RKTestFactory client]; NSDictionary *bodyParams = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:10], @"number", @"JSON String", @"string", nil]; @@ -931,11 +983,12 @@ - (void)testThatDELETERequestsAreNotConsideredCacheable assertThatBool([request isCacheable], is(equalToBool(NO))); } -- (void)testInvocationOfDidReceiveResponse { - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; +- (void)testInvocationOfDidReceiveResponse +{ + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; id loaderMock = [OCMockObject partialMockForObject:loader]; - NSURL* URL = [[RKTestFactory baseURL] URLByAppendingResourcePath:@"/200"]; - RKRequest* request = [[RKRequest alloc] initWithURL:URL]; + NSURL *URL = [[RKTestFactory baseURL] URLByAppendingResourcePath:@"/200"]; + RKRequest *request = [[RKRequest alloc] initWithURL:URL]; request.delegate = loaderMock; [[loaderMock expect] request:request didReceiveResponse:OCMOCK_ANY]; [request sendAsynchronously]; @@ -944,9 +997,10 @@ - (void)testInvocationOfDidReceiveResponse { [loaderMock verify]; } -- (void)testThatIsLoadingIsNoDuringDidFailWithErrorCallback { +- (void)testThatIsLoadingIsNoDuringDidFailWithErrorCallback +{ NSURL *URL = [[NSURL alloc] initWithString:@"http://localhost:8765"]; - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; RKClient *client = [RKClient clientWithBaseURL:URL]; RKRequest *request = [client requestWithResourcePath:@"/invalid"]; @@ -959,9 +1013,10 @@ - (void)testThatIsLoadingIsNoDuringDidFailWithErrorCallback { [loader waitForResponse]; } -- (void)testThatIsLoadedIsYesDuringDidFailWithErrorCallback { +- (void)testThatIsLoadedIsYesDuringDidFailWithErrorCallback +{ NSURL *URL = [[NSURL alloc] initWithString:@"http://localhost:8765"]; - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; RKClient *client = [RKClient clientWithBaseURL:URL]; RKRequest *request = [client requestWithResourcePath:@"/invalid"]; @@ -974,10 +1029,11 @@ - (void)testThatIsLoadedIsYesDuringDidFailWithErrorCallback { [loader waitForResponse]; } -- (void)testUnavailabilityOfResponseInDidFailWithErrorCallback { +- (void)testUnavailabilityOfResponseInDidFailWithErrorCallback +{ NSURL *URL = [[NSURL alloc] initWithString:@"http://localhost:8765"]; - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; - + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; + RKClient *client = [RKClient clientWithBaseURL:URL]; RKRequest *request = [client requestWithResourcePath:@"/invalid"]; request.method = RKRequestMethodGET; @@ -987,7 +1043,8 @@ - (void)testUnavailabilityOfResponseInDidFailWithErrorCallback { assertThat(request.response, is(nilValue())); } -- (void)testAvailabilityOfResponseWhenFailedDueTo500Response { +- (void)testAvailabilityOfResponseWhenFailedDueTo500Response +{ RKURL *URL = [[RKTestFactory baseURL] URLByAppendingResourcePath:@"/fail"]; RKRequest *request = [RKRequest requestWithURL:URL]; RKTestResponseLoader *responseLoader = [RKTestResponseLoader responseLoader]; diff --git a/Tests/Logic/Network/RKResponseTest.m b/Tests/Logic/Network/RKResponseTest.m index 0ba76ba11e..7c045be772 100644 --- a/Tests/Logic/Network/RKResponseTest.m +++ b/Tests/Logic/Network/RKResponseTest.m @@ -22,19 +22,21 @@ #import "RKResponse.h" @interface RKResponseTest : RKTestCase { - RKResponse* _response; + RKResponse *_response; } @end @implementation RKResponseTest -- (void)setUp { +- (void)setUp +{ _response = [[RKResponse alloc] init]; } -- (void)testShouldConsiderResponsesLessThanOneHudredOrGreaterThanSixHundredInvalid { - RKResponse* response = [[[RKResponse alloc] init] autorelease]; +- (void)testShouldConsiderResponsesLessThanOneHudredOrGreaterThanSixHundredInvalid +{ + RKResponse *response = [[[RKResponse alloc] init] autorelease]; id mock = [OCMockObject partialMockForObject:response]; NSInteger statusCode = 99; [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; @@ -44,8 +46,9 @@ - (void)testShouldConsiderResponsesLessThanOneHudredOrGreaterThanSixHundredInval assertThatBool([mock isInvalid], is(equalToBool(YES))); } -- (void)testShouldConsiderResponsesInTheOneHudredsInformational { - RKResponse* response = [[[RKResponse alloc] init] autorelease]; +- (void)testShouldConsiderResponsesInTheOneHudredsInformational +{ + RKResponse *response = [[[RKResponse alloc] init] autorelease]; id mock = [OCMockObject partialMockForObject:response]; NSInteger statusCode = 100; [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; @@ -55,8 +58,9 @@ - (void)testShouldConsiderResponsesInTheOneHudredsInformational { assertThatBool([mock isInformational], is(equalToBool(YES))); } -- (void)testShouldConsiderResponsesInTheTwoHundredsSuccessful { - RKResponse* response = [[[RKResponse alloc] init] autorelease]; +- (void)testShouldConsiderResponsesInTheTwoHundredsSuccessful +{ + RKResponse *response = [[[RKResponse alloc] init] autorelease]; id mock = [OCMockObject partialMockForObject:response]; NSInteger twoHundred = 200; [[[mock stub] andReturnValue:OCMOCK_VALUE(twoHundred)] statusCode]; @@ -66,8 +70,9 @@ - (void)testShouldConsiderResponsesInTheTwoHundredsSuccessful { assertThatBool([mock isSuccessful], is(equalToBool(YES))); } -- (void)testShouldConsiderResponsesInTheThreeHundredsRedirects { - RKResponse* response = [[[RKResponse alloc] init] autorelease]; +- (void)testShouldConsiderResponsesInTheThreeHundredsRedirects +{ + RKResponse *response = [[[RKResponse alloc] init] autorelease]; id mock = [OCMockObject partialMockForObject:response]; NSInteger statusCode = 300; [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; @@ -77,8 +82,9 @@ - (void)testShouldConsiderResponsesInTheThreeHundredsRedirects { assertThatBool([mock isRedirection], is(equalToBool(YES))); } -- (void)testShouldConsiderResponsesInTheFourHundredsClientErrors { - RKResponse* response = [[[RKResponse alloc] init] autorelease]; +- (void)testShouldConsiderResponsesInTheFourHundredsClientErrors +{ + RKResponse *response = [[[RKResponse alloc] init] autorelease]; id mock = [OCMockObject partialMockForObject:response]; NSInteger statusCode = 400; [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; @@ -88,8 +94,9 @@ - (void)testShouldConsiderResponsesInTheFourHundredsClientErrors { assertThatBool([mock isClientError], is(equalToBool(YES))); } -- (void)testShouldConsiderResponsesInTheFiveHundredsServerErrors { - RKResponse* response = [[[RKResponse alloc] init] autorelease]; +- (void)testShouldConsiderResponsesInTheFiveHundredsServerErrors +{ + RKResponse *response = [[[RKResponse alloc] init] autorelease]; id mock = [OCMockObject partialMockForObject:response]; NSInteger statusCode = 500; [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; @@ -99,56 +106,63 @@ - (void)testShouldConsiderResponsesInTheFiveHundredsServerErrors { assertThatBool([mock isServerError], is(equalToBool(YES))); } -- (void)testShouldConsiderATwoHundredResponseOK { - RKResponse* response = [[[RKResponse alloc] init] autorelease]; +- (void)testShouldConsiderATwoHundredResponseOK +{ + RKResponse *response = [[[RKResponse alloc] init] autorelease]; id mock = [OCMockObject partialMockForObject:response]; NSInteger statusCode = 200; [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; assertThatBool([mock isOK], is(equalToBool(YES))); } -- (void)testShouldConsiderATwoHundredAndOneResponseCreated { - RKResponse* response = [[[RKResponse alloc] init] autorelease]; +- (void)testShouldConsiderATwoHundredAndOneResponseCreated +{ + RKResponse *response = [[[RKResponse alloc] init] autorelease]; id mock = [OCMockObject partialMockForObject:response]; NSInteger statusCode = 201; [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; assertThatBool([mock isCreated], is(equalToBool(YES))); } -- (void)testShouldConsiderAFourOhThreeResponseForbidden { - RKResponse* response = [[[RKResponse alloc] init] autorelease]; +- (void)testShouldConsiderAFourOhThreeResponseForbidden +{ + RKResponse *response = [[[RKResponse alloc] init] autorelease]; id mock = [OCMockObject partialMockForObject:response]; NSInteger statusCode = 403; [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; assertThatBool([mock isForbidden], is(equalToBool(YES))); } -- (void)testShouldConsiderAFourOhFourResponseNotFound { - RKResponse* response = [[[RKResponse alloc] init] autorelease]; +- (void)testShouldConsiderAFourOhFourResponseNotFound +{ + RKResponse *response = [[[RKResponse alloc] init] autorelease]; id mock = [OCMockObject partialMockForObject:response]; NSInteger statusCode = 404; [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; assertThatBool([mock isNotFound], is(equalToBool(YES))); } -- (void)testShouldConsiderAFourOhNineResponseConflict { - RKResponse* response = [[[RKResponse alloc] init] autorelease]; +- (void)testShouldConsiderAFourOhNineResponseConflict +{ + RKResponse *response = [[[RKResponse alloc] init] autorelease]; id mock = [OCMockObject partialMockForObject:response]; NSInteger statusCode = 409; [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; assertThatBool([mock isConflict], is(equalToBool(YES))); } -- (void)testShouldConsiderAFourHundredAndTenResponseConflict { - RKResponse* response = [[[RKResponse alloc] init] autorelease]; +- (void)testShouldConsiderAFourHundredAndTenResponseConflict +{ + RKResponse *response = [[[RKResponse alloc] init] autorelease]; id mock = [OCMockObject partialMockForObject:response]; NSInteger statusCode = 410; [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; assertThatBool([mock isGone], is(equalToBool(YES))); } -- (void)testShouldConsiderVariousThreeHundredResponsesRedirect { - RKResponse* response = [[[RKResponse alloc] init] autorelease]; +- (void)testShouldConsiderVariousThreeHundredResponsesRedirect +{ + RKResponse *response = [[[RKResponse alloc] init] autorelease]; id mock = [OCMockObject partialMockForObject:response]; NSInteger statusCode = 301; [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; @@ -164,8 +178,9 @@ - (void)testShouldConsiderVariousThreeHundredResponsesRedirect { assertThatBool([mock isRedirect], is(equalToBool(YES))); } -- (void)testShouldConsiderVariousResponsesEmpty { - RKResponse* response = [[[RKResponse alloc] init] autorelease]; +- (void)testShouldConsiderVariousResponsesEmpty +{ + RKResponse *response = [[[RKResponse alloc] init] autorelease]; id mock = [OCMockObject partialMockForObject:response]; NSInteger statusCode = 201; [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; @@ -178,60 +193,67 @@ - (void)testShouldConsiderVariousResponsesEmpty { assertThatBool([mock isEmpty], is(equalToBool(YES))); } -- (void)testShouldMakeTheContentTypeHeaderAccessible { - RKResponse* response = [[[RKResponse alloc] init] autorelease]; +- (void)testShouldMakeTheContentTypeHeaderAccessible +{ + RKResponse *response = [[[RKResponse alloc] init] autorelease]; id mock = [OCMockObject partialMockForObject:response]; - NSDictionary* headers = [NSDictionary dictionaryWithObject:@"application/xml" forKey:@"Content-Type"]; + NSDictionary *headers = [NSDictionary dictionaryWithObject:@"application/xml" forKey:@"Content-Type"]; [[[mock stub] andReturn:headers] allHeaderFields]; assertThat([mock contentType], is(equalTo(@"application/xml"))); } // Should this return a string??? -- (void)testShouldMakeTheContentLengthHeaderAccessible { - RKResponse* response = [[[RKResponse alloc] init] autorelease]; +- (void)testShouldMakeTheContentLengthHeaderAccessible +{ + RKResponse *response = [[[RKResponse alloc] init] autorelease]; id mock = [OCMockObject partialMockForObject:response]; - NSDictionary* headers = [NSDictionary dictionaryWithObject:@"12345" forKey:@"Content-Length"]; + NSDictionary *headers = [NSDictionary dictionaryWithObject:@"12345" forKey:@"Content-Length"]; [[[mock stub] andReturn:headers] allHeaderFields]; assertThat([mock contentLength], is(equalTo(@"12345"))); } -- (void)testShouldMakeTheLocationHeaderAccessible { - RKResponse* response = [[[RKResponse alloc] init] autorelease]; +- (void)testShouldMakeTheLocationHeaderAccessible +{ + RKResponse *response = [[[RKResponse alloc] init] autorelease]; id mock = [OCMockObject partialMockForObject:response]; - NSDictionary* headers = [NSDictionary dictionaryWithObject:@"/foo/bar" forKey:@"Location"]; + NSDictionary *headers = [NSDictionary dictionaryWithObject:@"/foo/bar" forKey:@"Location"]; [[[mock stub] andReturn:headers] allHeaderFields]; assertThat([mock location], is(equalTo(@"/foo/bar"))); } -- (void)testShouldKnowIfItIsAnXMLResponse { - RKResponse* response = [[[RKResponse alloc] init] autorelease]; +- (void)testShouldKnowIfItIsAnXMLResponse +{ + RKResponse *response = [[[RKResponse alloc] init] autorelease]; id mock = [OCMockObject partialMockForObject:response]; - NSDictionary* headers = [NSDictionary dictionaryWithObject:@"application/xml" forKey:@"Content-Type"]; + NSDictionary *headers = [NSDictionary dictionaryWithObject:@"application/xml" forKey:@"Content-Type"]; [[[mock stub] andReturn:headers] allHeaderFields]; assertThatBool([mock isXML], is(equalToBool(YES))); } -- (void)testShouldKnowIfItIsAnJSONResponse { - RKResponse* response = [[[RKResponse alloc] init] autorelease]; +- (void)testShouldKnowIfItIsAnJSONResponse +{ + RKResponse *response = [[[RKResponse alloc] init] autorelease]; id mock = [OCMockObject partialMockForObject:response]; - NSDictionary* headers = [NSDictionary dictionaryWithObject:@"application/json" forKey:@"Content-Type"]; + NSDictionary *headers = [NSDictionary dictionaryWithObject:@"application/json" forKey:@"Content-Type"]; [[[mock stub] andReturn:headers] allHeaderFields]; assertThatBool([mock isJSON], is(equalToBool(YES))); } -- (void)testShouldReturnParseErrorsWhenParsedBodyFails { - RKResponse* response = [[[RKResponse alloc] init] autorelease]; +- (void)testShouldReturnParseErrorsWhenParsedBodyFails +{ + RKResponse *response = [[[RKResponse alloc] init] autorelease]; id mock = [OCMockObject partialMockForObject:response]; [[[mock stub] andReturn:@"sad;sdvjnk;"] bodyAsString]; [[[mock stub] andReturn:@"application/json"] MIMEType]; - NSError* error = nil; + NSError *error = nil; id object = [mock parsedBody:&error]; assertThat(object, is(nilValue())); assertThat(error, isNot(nilValue())); assertThat([error localizedDescription], is(equalTo(@"Unexpected token, wanted '{', '}', '[', ']', ',', ':', 'true', 'false', 'null', '\"STRING\"', 'NUMBER'."))); } -- (void)testShouldNotCrashOnFailureToParseBody { +- (void)testShouldNotCrashOnFailureToParseBody +{ RKResponse *response = [[RKResponse new] autorelease]; id mockResponse = [OCMockObject partialMockForObject:response]; [[[mockResponse stub] andReturn:@"test/fake"] MIMEType]; @@ -241,15 +263,16 @@ - (void)testShouldNotCrashOnFailureToParseBody { assertThat(parsedResponse, is(nilValue())); } -- (void)testShouldNotCrashWhenParserReturnsNilWithoutAnError { - RKResponse* response = [[[RKResponse alloc] init] autorelease]; +- (void)testShouldNotCrashWhenParserReturnsNilWithoutAnError +{ + RKResponse *response = [[[RKResponse alloc] init] autorelease]; id mockResponse = [OCMockObject partialMockForObject:response]; [[[mockResponse stub] andReturn:@""] bodyAsString]; [[[mockResponse stub] andReturn:RKMIMETypeJSON] MIMEType]; id mockParser = [OCMockObject mockForProtocol:@protocol(RKParser)]; id mockRegistry = [OCMockObject partialMockForObject:[RKParserRegistry sharedRegistry]]; [[[mockRegistry expect] andReturn:mockParser] parserForMIMEType:RKMIMETypeJSON]; - NSError* error = nil; + NSError *error = nil; [[[mockParser expect] andReturn:nil] objectFromString:@"" error:[OCMArg setTo:error]]; id object = [mockResponse parsedBody:&error]; [mockRegistry verify]; @@ -259,18 +282,20 @@ - (void)testShouldNotCrashWhenParserReturnsNilWithoutAnError { assertThat(error, is(nilValue())); } -- (void)testLoadingNonUTF8Charset { - RKClient* client = [RKTestFactory client]; - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; +- (void)testLoadingNonUTF8Charset +{ + RKClient *client = [RKTestFactory client]; + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; [client get:@"/encoding" delegate:loader]; [loader waitForResponse]; assertThat([loader.response bodyEncodingName], is(equalTo(@"us-ascii"))); assertThatInteger([loader.response bodyEncoding], is(equalToInteger(NSASCIIStringEncoding))); } -- (void)testFollowRedirect { - RKClient* client = [RKTestFactory client]; - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; +- (void)testFollowRedirect +{ + RKClient *client = [RKTestFactory client]; + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; [client get:@"/redirection" delegate:loader]; [loader waitForResponse]; assertThatInteger(loader.response.statusCode, is(equalToInteger(200))); @@ -279,11 +304,12 @@ - (void)testFollowRedirect { assertThat([body objectForKey:@"redirected"], is(equalTo([NSNumber numberWithBool:YES]))); } -- (void)testNoFollowRedirect { - RKClient* client = [RKTestFactory client]; - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; +- (void)testNoFollowRedirect +{ + RKClient *client = [RKTestFactory client]; + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; - RKRequest* request = [client requestWithResourcePath:@"/redirection"]; + RKRequest *request = [client requestWithResourcePath:@"/redirection"]; request.method = RKRequestMethodGET; request.followRedirect = NO; request.delegate = loader; @@ -295,9 +321,10 @@ - (void)testNoFollowRedirect { assertThat([loader.response.allHeaderFields objectForKey:@"Location"], is(equalTo(@"/redirection/target"))); } -- (void)testThatLoadingInvalidURLDoesNotCrashApp { +- (void)testThatLoadingInvalidURLDoesNotCrashApp +{ NSURL *URL = [[NSURL alloc] initWithString:@"http://localhost:5629"]; - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; RKClient *client = [RKClient clientWithBaseURL:URL]; RKRequest *request = [client requestWithResourcePath:@"/invalid"]; diff --git a/Tests/Logic/Network/RKURLTest.m b/Tests/Logic/Network/RKURLTest.m index c6f9531d96..03fa6c2579 100644 --- a/Tests/Logic/Network/RKURLTest.m +++ b/Tests/Logic/Network/RKURLTest.m @@ -27,8 +27,9 @@ @interface RKURLTest : RKTestCase @implementation RKURLTest -- (void)testShouldNotExplodeBecauseOfUnicodeCharacters { - NSException* failed = nil; +- (void)testShouldNotExplodeBecauseOfUnicodeCharacters +{ + NSException *failed = nil; @try { [RKURL URLWithBaseURLString:@"http://test.com" resourcePath:@"/places.json?category=Automóviles"]; } @@ -40,79 +41,94 @@ - (void)testShouldNotExplodeBecauseOfUnicodeCharacters { } } -- (void)testShouldEscapeQueryParameters { - NSDictionary* queryParams = [NSDictionary dictionaryWithObjectsAndKeys:@"What is your #1 e-mail?", @"question", @"john+restkit@gmail.com", @"answer", nil]; - RKURL* URL = [RKURL URLWithBaseURLString:@"http://restkit.org" resourcePath:@"/test" queryParameters:queryParams]; +- (void)testShouldEscapeQueryParameters +{ + NSDictionary *queryParams = [NSDictionary dictionaryWithObjectsAndKeys:@"What is your #1 e-mail?", @"question", @"john+restkit@gmail.com", @"answer", nil]; + RKURL *URL = [RKURL URLWithBaseURLString:@"http://restkit.org" resourcePath:@"/test" queryParameters:queryParams]; assertThat([URL absoluteString], is(equalTo(@"http://restkit.org/test?answer=john%2Brestkit%40gmail.com&question=What%20is%20your%20%231%20e-mail%3F"))); } -- (void)testShouldHandleNilQueryParameters { - RKURL* URL = [RKURL URLWithBaseURLString:@"http://restkit.org" resourcePath:@"/test" queryParameters:nil]; +- (void)testShouldHandleNilQueryParameters +{ + RKURL *URL = [RKURL URLWithBaseURLString:@"http://restkit.org" resourcePath:@"/test" queryParameters:nil]; assertThat([URL absoluteString], is(equalTo(@"http://restkit.org/test"))); } -- (void)testShouldHandleEmptyQueryParameters { - RKURL* URL = [RKURL URLWithBaseURLString:@"http://restkit.org" resourcePath:@"/test" queryParameters:[NSDictionary dictionary]]; +- (void)testShouldHandleEmptyQueryParameters +{ + RKURL *URL = [RKURL URLWithBaseURLString:@"http://restkit.org" resourcePath:@"/test" queryParameters:[NSDictionary dictionary]]; assertThat([URL absoluteString], is(equalTo(@"http://restkit.org/test"))); } -- (void)testShouldHandleResourcePathWithoutLeadingSlash { - RKURL* URL = [RKURL URLWithBaseURLString:@"http://restkit.org" resourcePath:@"test" queryParameters:nil]; +- (void)testShouldHandleResourcePathWithoutLeadingSlash +{ + RKURL *URL = [RKURL URLWithBaseURLString:@"http://restkit.org" resourcePath:@"test" queryParameters:nil]; assertThat([URL absoluteString], is(equalTo(@"http://restkit.org/test"))); } -- (void)testShouldHandleEmptyResourcePath { - RKURL* URL = [RKURL URLWithBaseURLString:@"http://restkit.org" resourcePath:@"" queryParameters:nil]; +- (void)testShouldHandleEmptyResourcePath +{ + RKURL *URL = [RKURL URLWithBaseURLString:@"http://restkit.org" resourcePath:@"" queryParameters:nil]; assertThat([URL absoluteString], is(equalTo(@"http://restkit.org"))); } -- (void)testShouldHandleBaseURLsWithAPath { - RKURL* URL = [RKURL URLWithBaseURLString:@"http://restkit.org/this" resourcePath:@"/test" queryParameters:nil]; +- (void)testShouldHandleBaseURLsWithAPath +{ + RKURL *URL = [RKURL URLWithBaseURLString:@"http://restkit.org/this" resourcePath:@"/test" queryParameters:nil]; assertThat([URL absoluteString], is(equalTo(@"http://restkit.org/this/test"))); } -- (void)testShouldSimplifyURLsWithSeveralSlashes { - RKURL* URL = [RKURL URLWithBaseURLString:@"http://restkit.org//this//" resourcePath:@"/test" queryParameters:nil]; +- (void)testShouldSimplifyURLsWithSeveralSlashes +{ + RKURL *URL = [RKURL URLWithBaseURLString:@"http://restkit.org//this//" resourcePath:@"/test" queryParameters:nil]; assertThat([URL absoluteString], is(equalTo(@"http://restkit.org/this/test"))); } -- (void)testShouldPreserveTrailingSlash { - RKURL* URL = [RKURL URLWithBaseURLString:@"http://restkit.org" resourcePath:@"/test/" queryParameters:nil]; +- (void)testShouldPreserveTrailingSlash +{ + RKURL *URL = [RKURL URLWithBaseURLString:@"http://restkit.org" resourcePath:@"/test/" queryParameters:nil]; assertThat([URL absoluteString], is(equalTo(@"http://restkit.org/test/"))); } -- (void)testShouldReturnTheMIMETypeForURL { +- (void)testShouldReturnTheMIMETypeForURL +{ NSURL *URL = [NSURL URLWithString:@"http://restkit.org/path/to/resource.xml"]; assertThat([URL MIMETypeForPathExtension], is(equalTo(@"application/xml"))); } -- (void)testInitializationFromStringIsEqualToAbsoluteString { +- (void)testInitializationFromStringIsEqualToAbsoluteString +{ RKURL *URL = [RKURL URLWithString:@"http://restkit.org"]; assertThat([URL absoluteString], is(equalTo(@"http://restkit.org"))); } -- (void)testInitializationFromStringHasSelfAsBaseURL { +- (void)testInitializationFromStringHasSelfAsBaseURL +{ RKURL *URL = [RKURL URLWithString:@"http://restkit.org"]; assertThat([[URL baseURL] absoluteString], is(equalTo(@"http://restkit.org"))); } -- (void)testInitializationFromStringHasNilResourcePath { +- (void)testInitializationFromStringHasNilResourcePath +{ RKURL *URL = [RKURL URLWithString:@"http://restkit.org"]; assertThat([URL resourcePath], is(nilValue())); } -- (void)testInitializationFromStringHasNilQueryParameters { +- (void)testInitializationFromStringHasNilQueryParameters +{ RKURL *URL = [RKURL URLWithString:@"http://restkit.org"]; assertThat([URL query], is(nilValue())); assertThat([URL queryParameters], is(nilValue())); } -- (void)testInitializationFromStringIncludingQueryParameters { +- (void)testInitializationFromStringIncludingQueryParameters +{ RKURL *URL = [RKURL URLWithString:@"http://restkit.org/foo?bar=1&this=that"]; assertThat([URL queryParameters], hasEntries(@"bar", equalTo(@"1"), @"this", equalTo(@"that"), nil)); } -- (void)testInitializationFromURLandResourcePathIncludingQueryParameters { +- (void)testInitializationFromURLandResourcePathIncludingQueryParameters +{ NSString *resourcePath = @"/bar?another=option"; RKURL *URL = [RKURL URLWithBaseURLString:@"http://restkit.org/foo?bar=1&this=that" resourcePath:resourcePath]; #if TARGET_OS_IPHONE @@ -125,39 +141,45 @@ - (void)testInitializationFromURLandResourcePathIncludingQueryParameters { @"another", equalTo(@"option"), nil)); } -- (void)testInitializationFromNSURL { +- (void)testInitializationFromNSURL +{ NSURL *URL = [NSURL URLWithString:@"http://restkit.org"]; RKURL *rkURL = [RKURL URLWithBaseURL:URL]; assertThat(URL, is(equalTo(rkURL))); } -- (void)testInitializationFromRKURL { +- (void)testInitializationFromRKURL +{ RKURL *URL = [RKURL URLWithString:@"http://restkit.org"]; RKURL *rkURL = [RKURL URLWithBaseURL:URL]; assertThat(URL, is(equalTo(rkURL))); } -- (void)testInitializationFromNSURLandAppendingOfResourcePath { +- (void)testInitializationFromNSURLandAppendingOfResourcePath +{ RKURL *URL = [RKURL URLWithString:@"http://restkit.org/"]; RKURL *rkURL = [RKURL URLWithBaseURL:URL resourcePath:@"/entries"]; assertThat([rkURL absoluteString], equalTo(@"http://restkit.org/entries")); } -- (void)testMergingOfAdditionalQueryParameters { +- (void)testMergingOfAdditionalQueryParameters +{ NSURL *URL = [NSURL URLWithString:@"http://restkit.org/search?title=Hacking"]; NSDictionary *params = [NSDictionary dictionaryWithObject:@"Computers" forKey:@"genre"]; RKURL *newURL = [RKURL URLWithBaseURL:URL resourcePath:nil queryParameters:params]; assertThat([newURL queryParameters], hasEntries(@"title", equalTo(@"Hacking"), @"genre", equalTo(@"Computers"), nil)); } -- (void)testReplacementOfExistingResourcePath { +- (void)testReplacementOfExistingResourcePath +{ RKURL *URL = [RKURL URLWithBaseURLString:@"http://restkit.org/" resourcePath:@"/articles"]; RKURL *newURL = [URL URLByReplacingResourcePath:@"/files"]; assertThat([newURL absoluteString], equalTo(@"http://restkit.org/files")); assertThat([newURL resourcePath], equalTo(@"/files")); } -- (void)testReplacementOfNilResourcePath { +- (void)testReplacementOfNilResourcePath +{ RKURL *URL = [RKURL URLWithString:@"http://restkit.org/whatever"]; assertThat([URL resourcePath], is(nilValue())); RKURL *newURL = [URL URLByReplacingResourcePath:@"/works"]; @@ -165,7 +187,8 @@ - (void)testReplacementOfNilResourcePath { assertThat([newURL absoluteString], is(equalTo(@"http://restkit.org/whatever/works"))); } -- (void)testInterpolationOfResourcePath { +- (void)testInterpolationOfResourcePath +{ RKURL *URL = [RKURL URLWithBaseURLString:@"http://restkit.org" resourcePath:@"/paginate?page=:page&perPage=:per_page"]; NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"1", @"page", @"25", @"per_page", nil]; RKURL *interpolatedURL = [URL URLByInterpolatingResourcePathWithObject:dictionary]; @@ -179,7 +202,8 @@ - (void)testInterpolationOfResourcePath { assertThat([interpolatedURL queryParameters], is(equalTo(queryParams))); } -- (void)testShouldProperlyHandleLongURLParameterValues { +- (void)testShouldProperlyHandleLongURLParameterValues +{ NSString *longResourcePath = @""; for (NSUInteger index = 0; index < 1050; index++) { longResourcePath = [longResourcePath stringByAppendingString:@"X"]; diff --git a/Tests/Logic/ObjectMapping/RKDynamicObjectMappingTest.m b/Tests/Logic/ObjectMapping/RKDynamicObjectMappingTest.m index ffe6a0c97d..2d4c6336e6 100644 --- a/Tests/Logic/ObjectMapping/RKDynamicObjectMappingTest.m +++ b/Tests/Logic/ObjectMapping/RKDynamicObjectMappingTest.m @@ -28,17 +28,18 @@ @interface RKDynamicObjectMappingTest : RKTestCase userID"))); } #pragma mark - RKObjectMapping Tests -- (void)testShouldDefineMappingFromAnElementToAProperty { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectAttributeMapping* idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; +- (void)testShouldDefineMappingFromAnElementToAProperty +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectAttributeMapping *idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; [mapping addAttributeMapping:idMapping]; assertThat([mapping mappingForKeyPath:@"id"], is(sameInstance(idMapping))); } -- (void)testShouldAddMappingsToAttributeMappings { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectAttributeMapping* idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; +- (void)testShouldAddMappingsToAttributeMappings +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectAttributeMapping *idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; [mapping addAttributeMapping:idMapping]; assertThatBool([mapping.mappings containsObject:idMapping], is(equalToBool(YES))); assertThatBool([mapping.attributeMappings containsObject:idMapping], is(equalToBool(YES))); } -- (void)testShouldAddMappingsToRelationshipMappings { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectRelationshipMapping* idMapping = [RKObjectRelationshipMapping mappingFromKeyPath:@"id" toKeyPath:@"userID" withMapping:nil]; +- (void)testShouldAddMappingsToRelationshipMappings +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectRelationshipMapping *idMapping = [RKObjectRelationshipMapping mappingFromKeyPath:@"id" toKeyPath:@"userID" withMapping:nil]; [mapping addRelationshipMapping:idMapping]; assertThatBool([mapping.mappings containsObject:idMapping], is(equalToBool(YES))); assertThatBool([mapping.relationshipMappings containsObject:idMapping], is(equalToBool(YES))); } -- (void)testShouldGenerateAttributeMappings { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; +- (void)testShouldGenerateAttributeMappings +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; assertThat([mapping mappingForKeyPath:@"name"], is(nilValue())); [mapping mapKeyPath:@"name" toAttribute:@"name"]; assertThat([mapping mappingForKeyPath:@"name"], isNot(nilValue())); } -- (void)testShouldGenerateRelationshipMappings { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectMapping* anotherMapping = [RKObjectMapping mappingForClass:[NSDictionary class]]; +- (void)testShouldGenerateRelationshipMappings +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectMapping *anotherMapping = [RKObjectMapping mappingForClass:[NSDictionary class]]; assertThat([mapping mappingForKeyPath:@"another"], is(nilValue())); [mapping mapRelationship:@"another" withMapping:anotherMapping]; assertThat([mapping mappingForKeyPath:@"another"], isNot(nilValue())); } -- (void)testShouldRemoveMappings { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectAttributeMapping* idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; +- (void)testShouldRemoveMappings +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectAttributeMapping *idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; [mapping addAttributeMapping:idMapping]; assertThat(mapping.mappings, hasItem(idMapping)); [mapping removeMapping:idMapping]; assertThat(mapping.mappings, isNot(hasItem(idMapping))); } -- (void)testShouldRemoveMappingsByKeyPath { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectAttributeMapping* idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; +- (void)testShouldRemoveMappingsByKeyPath +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectAttributeMapping *idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; [mapping addAttributeMapping:idMapping]; assertThat(mapping.mappings, hasItem(idMapping)); [mapping removeMappingForKeyPath:@"id"]; assertThat(mapping.mappings, isNot(hasItem(idMapping))); } -- (void)testShouldRemoveAllMappings { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; +- (void)testShouldRemoveAllMappings +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; [mapping mapAttributes:@"one", @"two", @"three", nil]; assertThat(mapping.mappings, hasCountOf(3)); [mapping removeAllMappings]; assertThat(mapping.mappings, is(empty())); } -- (void)testShouldGenerateAnInverseMappings { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; +- (void)testShouldGenerateAnInverseMappings +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; [mapping mapKeyPath:@"first_name" toAttribute:@"firstName"]; [mapping mapAttributes:@"city", @"state", @"zip", nil]; - RKObjectMapping* otherMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; + RKObjectMapping *otherMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; [otherMapping mapAttributes:@"street", nil]; [mapping mapRelationship:@"address" withMapping:otherMapping]; - RKObjectMapping* inverse = [mapping inverseMapping]; + RKObjectMapping *inverse = [mapping inverseMapping]; assertThat(inverse.objectClass, is(equalTo([NSMutableDictionary class]))); assertThat([inverse mappingForKeyPath:@"firstName"], isNot(nilValue())); } -- (void)testShouldLetYouRetrieveMappingsByAttribute { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectAttributeMapping* attributeMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"nameAttribute"]; +- (void)testShouldLetYouRetrieveMappingsByAttribute +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectAttributeMapping *attributeMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"nameAttribute"]; [mapping addAttributeMapping:attributeMapping]; assertThat([mapping mappingForAttribute:@"nameAttribute"], is(equalTo(attributeMapping))); } -- (void)testShouldLetYouRetrieveMappingsByRelationship { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectRelationshipMapping* relationshipMapping = [RKObjectRelationshipMapping mappingFromKeyPath:@"friend" toKeyPath:@"friendRelationship" withMapping:mapping]; +- (void)testShouldLetYouRetrieveMappingsByRelationship +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectRelationshipMapping *relationshipMapping = [RKObjectRelationshipMapping mappingFromKeyPath:@"friend" toKeyPath:@"friendRelationship" withMapping:mapping]; [mapping addRelationshipMapping:relationshipMapping]; assertThat([mapping mappingForRelationship:@"friendRelationship"], is(equalTo(relationshipMapping))); } #pragma mark - RKObjectMapper Tests -- (void)testShouldPerformBasicMapping { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectAttributeMapping* idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; +- (void)testShouldPerformBasicMapping +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectAttributeMapping *idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; [mapping addAttributeMapping:idMapping]; - RKObjectAttributeMapping* nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; + RKObjectAttributeMapping *nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; [mapping addAttributeMapping:nameMapping]; - RKObjectMapper* mapper = [RKObjectMapper new]; + RKObjectMapper *mapper = [RKObjectMapper new]; id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; - RKTestUser* user = [RKTestUser user]; + RKTestUser *user = [RKTestUser user]; BOOL success = [mapper mapFromObject:userInfo toObject:user atKeyPath:@"" usingMapping:mapping]; [mapper release]; assertThatBool(success, is(equalToBool(YES))); @@ -236,65 +254,69 @@ - (void)testShouldPerformBasicMapping { assertThat(user.name, is(equalTo(@"Blake Watters"))); } -- (void)testShouldMapACollectionOfSimpleObjectDictionaries { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectAttributeMapping* idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; +- (void)testShouldMapACollectionOfSimpleObjectDictionaries +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectAttributeMapping *idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; [mapping addAttributeMapping:idMapping]; - RKObjectAttributeMapping* nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; + RKObjectAttributeMapping *nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; [mapping addAttributeMapping:nameMapping]; - RKObjectMapper* mapper = [RKObjectMapper new]; + RKObjectMapper *mapper = [RKObjectMapper new]; id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"users.json"]; - NSArray* users = [mapper mapCollection:userInfo atKeyPath:@"" usingMapping:mapping]; + NSArray *users = [mapper mapCollection:userInfo atKeyPath:@"" usingMapping:mapping]; assertThatUnsignedInteger([users count], is(equalToInt(3))); - RKTestUser* blake = [users objectAtIndex:0]; + RKTestUser *blake = [users objectAtIndex:0]; assertThat(blake.name, is(equalTo(@"Blake Watters"))); [mapper release]; } -- (void)testShouldDetermineTheObjectMappingByConsultingTheMappingProviderWhenThereIsATargetObject { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectMappingProvider* provider = [[RKObjectMappingProvider new] autorelease]; +- (void)testShouldDetermineTheObjectMappingByConsultingTheMappingProviderWhenThereIsATargetObject +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; [provider setMapping:mapping forKeyPath:@""]; id mockProvider = [OCMockObject partialMockForObject:provider]; id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; - RKObjectMapper* mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:mockProvider]; + RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:mockProvider]; mapper.targetObject = [RKTestUser user]; [mapper performMapping]; [mockProvider verify]; } -- (void)testShouldAddAnErrorWhenTheKeyPathMappingAndObjectClassDoNotAgree { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectMappingProvider* provider = [[RKObjectMappingProvider new] autorelease]; +- (void)testShouldAddAnErrorWhenTheKeyPathMappingAndObjectClassDoNotAgree +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; [provider setMapping:mapping forKeyPath:@""]; id mockProvider = [OCMockObject partialMockForObject:provider]; id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; - RKObjectMapper* mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:mockProvider]; + RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:mockProvider]; mapper.targetObject = [NSDictionary new]; [mapper performMapping]; assertThatUnsignedInteger([mapper errorCount], is(equalToInt(1))); } -- (void)testShouldMapToATargetObject { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectAttributeMapping* idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; +- (void)testShouldMapToATargetObject +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectAttributeMapping *idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; [mapping addAttributeMapping:idMapping]; - RKObjectAttributeMapping* nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; + RKObjectAttributeMapping *nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; [mapping addAttributeMapping:nameMapping]; - RKObjectMappingProvider* provider = [[RKObjectMappingProvider new] autorelease]; + RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; [provider setMapping:mapping forKeyPath:@""]; id mockProvider = [OCMockObject partialMockForObject:provider]; id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; - RKObjectMapper* mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:mockProvider]; - RKTestUser* user = [RKTestUser user]; + RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:mockProvider]; + RKTestUser *user = [RKTestUser user]; mapper.targetObject = user; - RKObjectMappingResult* result = [mapper performMapping]; + RKObjectMappingResult *result = [mapper performMapping]; [mockProvider verify]; assertThat(result, isNot(nilValue())); @@ -302,88 +324,93 @@ - (void)testShouldMapToATargetObject { assertThat(user.name, is(equalTo(@"Blake Watters"))); } -- (void)testShouldCreateANewInstanceOfTheAppropriateDestinationObjectWhenThereIsNoTargetObject { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectAttributeMapping* nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; +- (void)testShouldCreateANewInstanceOfTheAppropriateDestinationObjectWhenThereIsNoTargetObject +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectAttributeMapping *nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; [mapping addAttributeMapping:nameMapping]; - RKObjectMappingProvider* provider = [[RKObjectMappingProvider new] autorelease]; + RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; [provider setMapping:mapping forKeyPath:@""]; id mockProvider = [OCMockObject partialMockForObject:provider]; id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; - RKObjectMapper* mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:mockProvider]; + RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:mockProvider]; id mappingResult = [[mapper performMapping] asObject]; assertThatBool([mappingResult isKindOfClass:[RKTestUser class]], is(equalToBool(YES))); } -- (void)testShouldDetermineTheMappingClassForAKeyPathByConsultingTheMappingProviderWhenMappingADictionaryWithoutATargetObject { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectMappingProvider* provider = [[RKObjectMappingProvider new] autorelease]; +- (void)testShouldDetermineTheMappingClassForAKeyPathByConsultingTheMappingProviderWhenMappingADictionaryWithoutATargetObject +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; [provider setMapping:mapping forKeyPath:@""]; id mockProvider = [OCMockObject partialMockForObject:provider]; [[mockProvider expect] valueForContext:RKObjectMappingProviderContextObjectsByKeyPath]; id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; - RKObjectMapper* mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:mockProvider]; + RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:mockProvider]; [mapper performMapping]; [mockProvider verify]; } -- (void)testShouldMapWithoutATargetMapping { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectAttributeMapping* idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; +- (void)testShouldMapWithoutATargetMapping +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectAttributeMapping *idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; [mapping addAttributeMapping:idMapping]; - RKObjectAttributeMapping* nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; + RKObjectAttributeMapping *nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; [mapping addAttributeMapping:nameMapping]; - RKObjectMappingProvider* provider = [[RKObjectMappingProvider new] autorelease]; + RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; [provider setMapping:mapping forKeyPath:@""]; id mockProvider = [OCMockObject partialMockForObject:provider]; id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; - RKObjectMapper* mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:mockProvider]; - RKTestUser* user = [[mapper performMapping] asObject]; + RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:mockProvider]; + RKTestUser *user = [[mapper performMapping] asObject]; assertThatBool([user isKindOfClass:[RKTestUser class]], is(equalToBool(YES))); assertThat(user.name, is(equalTo(@"Blake Watters"))); } -- (void)testShouldMapACollectionOfObjects { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectAttributeMapping* idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; +- (void)testShouldMapACollectionOfObjects +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectAttributeMapping *idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; [mapping addAttributeMapping:idMapping]; - RKObjectAttributeMapping* nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; + RKObjectAttributeMapping *nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; [mapping addAttributeMapping:nameMapping]; - RKObjectMappingProvider* provider = [[RKObjectMappingProvider new] autorelease]; + RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; [provider setMapping:mapping forKeyPath:@""]; id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"users.json"]; - RKObjectMapper* mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; - RKObjectMappingResult* result = [mapper performMapping]; - NSArray* users = [result asCollection]; + RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; + RKObjectMappingResult *result = [mapper performMapping]; + NSArray *users = [result asCollection]; assertThatBool([users isKindOfClass:[NSArray class]], is(equalToBool(YES))); assertThatUnsignedInteger([users count], is(equalToInt(3))); - RKTestUser* user = [users objectAtIndex:0]; + RKTestUser *user = [users objectAtIndex:0]; assertThatBool([user isKindOfClass:[RKTestUser class]], is(equalToBool(YES))); assertThat(user.name, is(equalTo(@"Blake Watters"))); } -- (void)testShouldMapACollectionOfObjectsWithDynamicKeys { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; +- (void)testShouldMapACollectionOfObjectsWithDynamicKeys +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; mapping.forceCollectionMapping = YES; [mapping mapKeyOfNestedDictionaryToAttribute:@"name"]; - RKObjectAttributeMapping* idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"(name).id" toKeyPath:@"userID"]; + RKObjectAttributeMapping *idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"(name).id" toKeyPath:@"userID"]; [mapping addAttributeMapping:idMapping]; - RKObjectMappingProvider* provider = [[RKObjectMappingProvider new] autorelease]; + RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; [provider setMapping:mapping forKeyPath:@"users"]; id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"DynamicKeys.json"]; - RKObjectMapper* mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; - RKObjectMappingResult* result = [mapper performMapping]; - NSArray* users = [result asCollection]; + RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; + RKObjectMappingResult *result = [mapper performMapping]; + NSArray *users = [result asCollection]; assertThatBool([users isKindOfClass:[NSArray class]], is(equalToBool(YES))); assertThatUnsignedInteger([users count], is(equalToInt(2))); - RKTestUser* user = [users objectAtIndex:0]; + RKTestUser *user = [users objectAtIndex:0]; assertThatBool([user isKindOfClass:[RKTestUser class]], is(equalToBool(YES))); assertThat(user.name, is(equalTo(@"blake"))); user = [users objectAtIndex:1]; @@ -391,24 +418,25 @@ - (void)testShouldMapACollectionOfObjectsWithDynamicKeys { assertThat(user.name, is(equalTo(@"rachit"))); } -- (void)testShouldMapACollectionOfObjectsWithDynamicKeysAndRelationships { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; +- (void)testShouldMapACollectionOfObjectsWithDynamicKeysAndRelationships +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; mapping.forceCollectionMapping = YES; [mapping mapKeyOfNestedDictionaryToAttribute:@"name"]; - RKObjectMapping* addressMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; + RKObjectMapping *addressMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; [addressMapping mapAttributes:@"city", @"state", nil]; [mapping mapKeyPath:@"(name).address" toRelationship:@"address" withMapping:addressMapping]; - RKObjectMappingProvider* provider = [[RKObjectMappingProvider new] autorelease]; + RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; [provider setMapping:mapping forKeyPath:@"users"]; id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"DynamicKeysWithRelationship.json"]; - RKObjectMapper* mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; - RKObjectMappingResult* result = [mapper performMapping]; - NSArray* users = [result asCollection]; + RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; + RKObjectMappingResult *result = [mapper performMapping]; + NSArray *users = [result asCollection]; assertThatBool([users isKindOfClass:[NSArray class]], is(equalToBool(YES))); assertThatUnsignedInteger([users count], is(equalToInt(2))); - RKTestUser* user = [users objectAtIndex:0]; + RKTestUser *user = [users objectAtIndex:0]; assertThatBool([user isKindOfClass:[RKTestUser class]], is(equalToBool(YES))); assertThat(user.name, is(equalTo(@"blake"))); user = [users objectAtIndex:1]; @@ -418,17 +446,18 @@ - (void)testShouldMapACollectionOfObjectsWithDynamicKeysAndRelationships { assertThat(user.address.city, is(equalTo(@"New York"))); } -- (void)testShouldMapANestedArrayOfObjectsWithDynamicKeysAndArrayRelationships { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKExampleGroupWithUserArray class]]; +- (void)testShouldMapANestedArrayOfObjectsWithDynamicKeysAndArrayRelationships +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKExampleGroupWithUserArray class]]; [mapping mapAttributes:@"name", nil]; - RKObjectMapping* userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; userMapping.forceCollectionMapping = YES; [userMapping mapKeyOfNestedDictionaryToAttribute:@"name"]; [mapping mapKeyPath:@"users" toRelationship:@"users" withMapping:userMapping]; - RKObjectMapping* addressMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; + RKObjectMapping *addressMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; [addressMapping mapAttributes: @"city", @"city", @"state", @"state", @@ -436,22 +465,22 @@ - (void)testShouldMapANestedArrayOfObjectsWithDynamicKeysAndArrayRelationships { nil ]; [userMapping mapKeyPath:@"(name).address" toRelationship:@"address" withMapping:addressMapping]; - RKObjectMappingProvider* provider = [[RKObjectMappingProvider new] autorelease]; + RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; [provider setMapping:mapping forKeyPath:@"groups"]; id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"DynamicKeysWithNestedRelationship.json"]; - RKObjectMapper* mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; - RKObjectMappingResult* result = [mapper performMapping]; + RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; + RKObjectMappingResult *result = [mapper performMapping]; - NSArray* groups = [result asCollection]; + NSArray *groups = [result asCollection]; assertThatBool([groups isKindOfClass:[NSArray class]], is(equalToBool(YES))); assertThatUnsignedInteger([groups count], is(equalToInt(2))); - RKExampleGroupWithUserArray* group = [groups objectAtIndex:0]; + RKExampleGroupWithUserArray *group = [groups objectAtIndex:0]; assertThatBool([group isKindOfClass:[RKExampleGroupWithUserArray class]], is(equalToBool(YES))); assertThat(group.name, is(equalTo(@"restkit"))); - NSArray * users = group.users; - RKTestUser* user = [users objectAtIndex:0]; + NSArray *users = group.users; + RKTestUser *user = [users objectAtIndex:0]; assertThatBool([user isKindOfClass:[RKTestUser class]], is(equalToBool(YES))); assertThat(user.name, is(equalTo(@"blake"))); user = [users objectAtIndex:1]; @@ -473,17 +502,18 @@ - (void)testShouldMapANestedArrayOfObjectsWithDynamicKeysAndArrayRelationships { assertThat(user.address.country, is(equalTo(@"Sweden"))); } -- (void)testShouldMapANestedArrayOfObjectsWithDynamicKeysAndSetRelationships { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKExampleGroupWithUserSet class]]; +- (void)testShouldMapANestedArrayOfObjectsWithDynamicKeysAndSetRelationships +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKExampleGroupWithUserSet class]]; [mapping mapAttributes:@"name", nil]; - RKObjectMapping* userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; userMapping.forceCollectionMapping = YES; [userMapping mapKeyOfNestedDictionaryToAttribute:@"name"]; [mapping mapKeyPath:@"users" toRelationship:@"users" withMapping:userMapping]; - RKObjectMapping* addressMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; + RKObjectMapping *addressMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; [addressMapping mapAttributes: @"city", @"city", @"state", @"state", @@ -491,26 +521,26 @@ - (void)testShouldMapANestedArrayOfObjectsWithDynamicKeysAndSetRelationships { nil ]; [userMapping mapKeyPath:@"(name).address" toRelationship:@"address" withMapping:addressMapping]; - RKObjectMappingProvider* provider = [[RKObjectMappingProvider new] autorelease]; + RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; [provider setMapping:mapping forKeyPath:@"groups"]; id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"DynamicKeysWithNestedRelationship.json"]; - RKObjectMapper* mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; - RKObjectMappingResult* result = [mapper performMapping]; + RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; + RKObjectMappingResult *result = [mapper performMapping]; - NSArray* groups = [result asCollection]; + NSArray *groups = [result asCollection]; assertThatBool([groups isKindOfClass:[NSArray class]], is(equalToBool(YES))); assertThatUnsignedInteger([groups count], is(equalToInt(2))); - RKExampleGroupWithUserSet* group = [groups objectAtIndex:0]; + RKExampleGroupWithUserSet *group = [groups objectAtIndex:0]; assertThatBool([group isKindOfClass:[RKExampleGroupWithUserSet class]], is(equalToBool(YES))); assertThat(group.name, is(equalTo(@"restkit"))); - NSSortDescriptor * sortByName =[[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES] autorelease]; - NSArray * descriptors = [NSArray arrayWithObject:sortByName];; - NSArray * users = [group.users sortedArrayUsingDescriptors:descriptors]; - RKTestUser* user = [users objectAtIndex:0]; + NSSortDescriptor *sortByName = [[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES] autorelease]; + NSArray *descriptors = [NSArray arrayWithObject:sortByName];; + NSArray *users = [group.users sortedArrayUsingDescriptors:descriptors]; + RKTestUser *user = [users objectAtIndex:0]; assertThatBool([user isKindOfClass:[RKTestUser class]], is(equalToBool(YES))); assertThat(user.name, is(equalTo(@"blake"))); user = [users objectAtIndex:1]; @@ -533,76 +563,81 @@ - (void)testShouldMapANestedArrayOfObjectsWithDynamicKeysAndSetRelationships { } -- (void)testShouldBeAbleToMapFromAUserObjectToADictionary { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; - RKObjectAttributeMapping* idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"userID" toKeyPath:@"id"]; +- (void)testShouldBeAbleToMapFromAUserObjectToADictionary +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; + RKObjectAttributeMapping *idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"userID" toKeyPath:@"id"]; [mapping addAttributeMapping:idMapping]; - RKObjectAttributeMapping* nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; + RKObjectAttributeMapping *nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; [mapping addAttributeMapping:nameMapping]; - RKObjectMappingProvider* provider = [[RKObjectMappingProvider new] autorelease]; + RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; [provider setMapping:mapping forKeyPath:@""]; - RKTestUser* user = [RKTestUser user]; + RKTestUser *user = [RKTestUser user]; user.name = @"Blake Watters"; user.userID = [NSNumber numberWithInt:123]; - RKObjectMapper* mapper = [RKObjectMapper mapperWithObject:user mappingProvider:provider]; - RKObjectMappingResult* result = [mapper performMapping]; - NSDictionary* userInfo = [result asObject]; + RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:user mappingProvider:provider]; + RKObjectMappingResult *result = [mapper performMapping]; + NSDictionary *userInfo = [result asObject]; assertThatBool([userInfo isKindOfClass:[NSDictionary class]], is(equalToBool(YES))); assertThat([userInfo valueForKey:@"name"], is(equalTo(@"Blake Watters"))); } -- (void)testShouldMapRegisteredSubKeyPathsOfAnUnmappableDictionaryAndReturnTheResults { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectAttributeMapping* idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; +- (void)testShouldMapRegisteredSubKeyPathsOfAnUnmappableDictionaryAndReturnTheResults +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectAttributeMapping *idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; [mapping addAttributeMapping:idMapping]; - RKObjectAttributeMapping* nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; + RKObjectAttributeMapping *nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; [mapping addAttributeMapping:nameMapping]; - RKObjectMappingProvider* provider = [[RKObjectMappingProvider new] autorelease]; + RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; [provider setMapping:mapping forKeyPath:@"user"]; id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"nested_user.json"]; - RKObjectMapper* mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; - NSDictionary* dictionary = [[mapper performMapping] asDictionary]; + RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; + NSDictionary *dictionary = [[mapper performMapping] asDictionary]; assertThatBool([dictionary isKindOfClass:[NSDictionary class]], is(equalToBool(YES))); - RKTestUser* user = [dictionary objectForKey:@"user"]; + RKTestUser *user = [dictionary objectForKey:@"user"]; assertThat(user, isNot(nilValue())); assertThat(user.name, is(equalTo(@"Blake Watters"))); } #pragma mark Mapping Error States -- (void)testShouldAddAnErrorWhenYouTryToMapAnArrayToATargetObject { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectAttributeMapping* idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; +- (void)testShouldAddAnErrorWhenYouTryToMapAnArrayToATargetObject +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectAttributeMapping *idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; [mapping addAttributeMapping:idMapping]; - RKObjectAttributeMapping* nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; + RKObjectAttributeMapping *nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; [mapping addAttributeMapping:nameMapping]; - RKObjectMappingProvider* provider = [[RKObjectMappingProvider new] autorelease]; + RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; [provider setMapping:mapping forKeyPath:@""]; id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"users.json"]; - RKObjectMapper* mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; + RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; mapper.targetObject = [RKTestUser user]; [mapper performMapping]; assertThatUnsignedInteger([mapper errorCount], is(equalToInt(1))); assertThatInteger([[mapper.errors objectAtIndex:0] code], is(equalToInt(RKObjectMapperErrorObjectMappingTypeMismatch))); } -- (void)testShouldAddAnErrorWhenAttemptingToMapADictionaryWithoutAnObjectMapping { +- (void)testShouldAddAnErrorWhenAttemptingToMapADictionaryWithoutAnObjectMapping +{ id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; - RKObjectMappingProvider* provider = [[RKObjectMappingProvider new] autorelease]; - RKObjectMapper* mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; + RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; + RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; [mapper performMapping]; assertThatUnsignedInteger([mapper errorCount], is(equalToInt(1))); assertThat([[mapper.errors objectAtIndex:0] localizedDescription], is(equalTo(@"Could not find an object mapping for keyPath: ''"))); } -- (void)testShouldAddAnErrorWhenAttemptingToMapACollectionWithoutAnObjectMapping { - RKObjectMappingProvider* provider = [[RKObjectMappingProvider new] autorelease]; +- (void)testShouldAddAnErrorWhenAttemptingToMapACollectionWithoutAnObjectMapping +{ + RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"users.json"]; - RKObjectMapper* mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; + RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; [mapper performMapping]; assertThatUnsignedInteger([mapper errorCount], is(equalToInt(1))); assertThat([[mapper.errors objectAtIndex:0] localizedDescription], is(equalTo(@"Could not find an object mapping for keyPath: ''"))); @@ -610,28 +645,30 @@ - (void)testShouldAddAnErrorWhenAttemptingToMapACollectionWithoutAnObjectMapping #pragma mark RKObjectMapperDelegate Tests -- (void)testShouldInformTheDelegateWhenMappingBegins { +- (void)testShouldInformTheDelegateWhenMappingBegins +{ id mockDelegate = [OCMockObject niceMockForProtocol:@protocol(RKObjectMapperDelegate)]; - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectMappingProvider* provider = [[RKObjectMappingProvider new] autorelease]; + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; [provider setMapping:mapping forKeyPath:@""]; id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"users.json"]; - RKObjectMapper* mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; + RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; [[mockDelegate expect] objectMapperWillBeginMapping:mapper]; mapper.delegate = mockDelegate; [mapper performMapping]; [mockDelegate verify]; } -- (void)testShouldInformTheDelegateWhenMappingEnds { +- (void)testShouldInformTheDelegateWhenMappingEnds +{ id mockDelegate = [OCMockObject niceMockForProtocol:@protocol(RKObjectMapperDelegate)]; - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectMappingProvider* provider = [[RKObjectMappingProvider new] autorelease]; + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; [provider setMapping:mapping forKeyPath:@""]; id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"users.json"]; - RKObjectMapper* mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; + RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; [[mockDelegate stub] objectMapperWillBeginMapping:mapper]; [[mockDelegate expect] objectMapperDidFinishMapping:mapper]; mapper.delegate = mockDelegate; @@ -639,27 +676,29 @@ - (void)testShouldInformTheDelegateWhenMappingEnds { [mockDelegate verify]; } -- (void)testShouldInformTheDelegateWhenCheckingForObjectMappingForKeyPathIsSuccessful { +- (void)testShouldInformTheDelegateWhenCheckingForObjectMappingForKeyPathIsSuccessful +{ id mockDelegate = [OCMockObject niceMockForProtocol:@protocol(RKObjectMapperDelegate)]; - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectMappingProvider* provider = [[RKObjectMappingProvider new] autorelease]; + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; [provider setMapping:mapping forKeyPath:@""]; id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; - RKObjectMapper* mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; + RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; [[mockDelegate expect] objectMapper:mapper didFindMappableObject:[OCMArg any] atKeyPath:@""withMapping:mapping]; mapper.delegate = mockDelegate; [mapper performMapping]; [mockDelegate verify]; } -- (void)testShouldInformTheDelegateWhenCheckingForObjectMappingForKeyPathIsNotSuccessful { - RKObjectMappingProvider* provider = [[RKObjectMappingProvider new] autorelease]; - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; +- (void)testShouldInformTheDelegateWhenCheckingForObjectMappingForKeyPathIsNotSuccessful +{ + RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; [provider setMapping:mapping forKeyPath:@"users"]; id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; - RKObjectMapper* mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; + RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; id mockDelegate = [OCMockObject niceMockForProtocol:@protocol(RKObjectMapperDelegate)]; [[mockDelegate expect] objectMapper:mapper didNotFindMappableObjectAtKeyPath:@"users"]; mapper.delegate = mockDelegate; @@ -667,63 +706,68 @@ - (void)testShouldInformTheDelegateWhenCheckingForObjectMappingForKeyPathIsNotSu [mockDelegate verify]; } -- (void)testShouldInformTheDelegateOfError { +- (void)testShouldInformTheDelegateOfError +{ id mockProvider = [OCMockObject niceMockForClass:[RKObjectMappingProvider class]]; id mockDelegate = [OCMockObject niceMockForProtocol:@protocol(RKObjectMapperDelegate)]; id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"users.json"]; - RKObjectMapper* mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:mockProvider]; + RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:mockProvider]; [[mockDelegate expect] objectMapper:mapper didAddError:[OCMArg isNotNil]]; mapper.delegate = mockDelegate; [mapper performMapping]; [mockDelegate verify]; } -- (void)testShouldNotifyTheDelegateWhenItWillMapAnObject { - RKObjectMappingProvider* provider = [[RKObjectMappingProvider new] autorelease]; - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; +- (void)testShouldNotifyTheDelegateWhenItWillMapAnObject +{ + RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; [provider setMapping:mapping forKeyPath:@""]; id mockDelegate = [OCMockObject niceMockForProtocol:@protocol(RKObjectMapperDelegate)]; id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; - RKObjectMapper* mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; + RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; [[mockDelegate expect] objectMapper:mapper willMapFromObject:userInfo toObject:[OCMArg any] atKeyPath:@"" usingMapping:mapping]; mapper.delegate = mockDelegate; [mapper performMapping]; [mockDelegate verify]; } -- (void)testShouldNotifyTheDelegateWhenItDidMapAnObject { +- (void)testShouldNotifyTheDelegateWhenItDidMapAnObject +{ id mockDelegate = [OCMockObject niceMockForProtocol:@protocol(RKObjectMapperDelegate)]; - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectAttributeMapping* nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectAttributeMapping *nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; [mapping addAttributeMapping:nameMapping]; - RKObjectMappingProvider* provider = [[RKObjectMappingProvider new] autorelease]; + RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; [provider setMapping:mapping forKeyPath:@""]; id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; - RKObjectMapper* mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; + RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; [[mockDelegate expect] objectMapper:mapper didMapFromObject:userInfo toObject:[OCMArg any] atKeyPath:@"" usingMapping:mapping]; mapper.delegate = mockDelegate; [mapper performMapping]; [mockDelegate verify]; } -- (BOOL)fakeValidateValue:(inout id *)ioValue forKeyPath:(NSString *)inKey error:(out NSError **)outError { +- (BOOL)fakeValidateValue:(inout id *)ioValue forKeyPath:(NSString *)inKey error:(out NSError **)outError +{ *outError = [NSError errorWithDomain:RKErrorDomain code:1234 userInfo:nil]; return NO; } -- (void)testShouldNotifyTheDelegateWhenItFailedToMapAnObject { +- (void)testShouldNotifyTheDelegateWhenItFailedToMapAnObject +{ id mockDelegate = [OCMockObject niceMockForProtocol:@protocol(RKObjectMapperDelegate)]; - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:NSClassFromString(@"OCPartialMockObject")]; + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:NSClassFromString(@"OCPartialMockObject")]; [mapping mapAttributes:@"name", nil]; - RKObjectMappingProvider* provider = [[RKObjectMappingProvider new] autorelease]; + RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; [provider setMapping:mapping forKeyPath:@""]; id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; - RKObjectMapper* mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; - RKTestUser* exampleUser = [[RKTestUser new] autorelease]; + RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; + RKTestUser *exampleUser = [[RKTestUser new] autorelease]; id mockObject = [OCMockObject partialMockForObject:exampleUser]; [[[mockObject expect] andCall:@selector(fakeValidateValue:forKeyPath:error:) onObject:self] validateValue:[OCMArg anyPointer] forKeyPath:OCMOCK_ANY error:[OCMArg anyPointer]]; mapper.targetObject = mockObject; @@ -736,53 +780,56 @@ - (void)testShouldNotifyTheDelegateWhenItFailedToMapAnObject { #pragma mark - RKObjectMappingOperationTests -- (void)testShouldBeAbleToMapADictionaryToAUser { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; - RKObjectAttributeMapping* idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; +- (void)testShouldBeAbleToMapADictionaryToAUser +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; + RKObjectAttributeMapping *idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; [mapping addAttributeMapping:idMapping]; - RKObjectAttributeMapping* nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; + RKObjectAttributeMapping *nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; [mapping addAttributeMapping:nameMapping]; - NSMutableDictionary* dictionary = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:123], @"id", @"Blake Watters", @"name", nil]; - RKTestUser* user = [RKTestUser user]; + NSMutableDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:123], @"id", @"Blake Watters", @"name", nil]; + RKTestUser *user = [RKTestUser user]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; [operation performMapping:nil]; assertThat(user.name, is(equalTo(@"Blake Watters"))); assertThatInt([user.userID intValue], is(equalToInt(123))); [operation release]; } -- (void)testShouldConsiderADictionaryContainingOnlyNullValuesForKeysMappable { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; - RKObjectAttributeMapping* idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; +- (void)testShouldConsiderADictionaryContainingOnlyNullValuesForKeysMappable +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; + RKObjectAttributeMapping *idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; [mapping addAttributeMapping:idMapping]; - RKObjectAttributeMapping* nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; + RKObjectAttributeMapping *nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; [mapping addAttributeMapping:nameMapping]; - NSMutableDictionary* dictionary = [NSDictionary dictionaryWithObjectsAndKeys:[NSNull null], @"name", nil]; - RKTestUser* user = [RKTestUser user]; + NSMutableDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:[NSNull null], @"name", nil]; + RKTestUser *user = [RKTestUser user]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; BOOL success = [operation performMapping:nil]; assertThatBool(success, is(equalToBool(YES))); assertThat(user.name, is(nilValue())); [operation release]; } -- (void)testShouldBeAbleToMapAUserToADictionary { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; - RKObjectAttributeMapping* idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"userID" toKeyPath:@"id"]; +- (void)testShouldBeAbleToMapAUserToADictionary +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; + RKObjectAttributeMapping *idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"userID" toKeyPath:@"id"]; [mapping addAttributeMapping:idMapping]; - RKObjectAttributeMapping* nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; + RKObjectAttributeMapping *nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; [mapping addAttributeMapping:nameMapping]; - RKTestUser* user = [RKTestUser user]; + RKTestUser *user = [RKTestUser user]; user.name = @"Blake Watters"; user.userID = [NSNumber numberWithInt:123]; - NSMutableDictionary* dictionary = [NSMutableDictionary dictionary]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:user destinationObject:dictionary mapping:mapping]; + NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:user destinationObject:dictionary mapping:mapping]; BOOL success = [operation performMapping:nil]; assertThatBool(success, is(equalToBool(YES))); assertThat([dictionary valueForKey:@"name"], is(equalTo(@"Blake Watters"))); @@ -790,56 +837,59 @@ - (void)testShouldBeAbleToMapAUserToADictionary { [operation release]; } -- (void)testShouldReturnNoWithoutErrorWhenGivenASourceObjectThatContainsNoMappableKeys { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; - RKObjectAttributeMapping* idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; +- (void)testShouldReturnNoWithoutErrorWhenGivenASourceObjectThatContainsNoMappableKeys +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; + RKObjectAttributeMapping *idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; [mapping addAttributeMapping:idMapping]; - RKObjectAttributeMapping* nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; + RKObjectAttributeMapping *nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; [mapping addAttributeMapping:nameMapping]; - NSMutableDictionary* dictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"blue", @"favorite_color", @"coffee", @"preferred_beverage", nil]; - RKTestUser* user = [RKTestUser user]; + NSMutableDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"blue", @"favorite_color", @"coffee", @"preferred_beverage", nil]; + RKTestUser *user = [RKTestUser user]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; - NSError* error = nil; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + NSError *error = nil; BOOL success = [operation performMapping:&error]; assertThatBool(success, is(equalToBool(NO))); assertThat(error, is(nilValue())); [operation release]; } -- (void)testShouldInformTheDelegateOfAnErrorWhenMappingFailsBecauseThereIsNoMappableContent { +- (void)testShouldInformTheDelegateOfAnErrorWhenMappingFailsBecauseThereIsNoMappableContent +{ id mockDelegate = [OCMockObject niceMockForProtocol:@protocol(RKObjectMappingOperationDelegate)]; - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; - RKObjectAttributeMapping* idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; + RKObjectAttributeMapping *idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; [mapping addAttributeMapping:idMapping]; - RKObjectAttributeMapping* nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; + RKObjectAttributeMapping *nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; [mapping addAttributeMapping:nameMapping]; - NSMutableDictionary* dictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"blue", @"favorite_color", @"coffee", @"preferred_beverage", nil]; - RKTestUser* user = [RKTestUser user]; + NSMutableDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"blue", @"favorite_color", @"coffee", @"preferred_beverage", nil]; + RKTestUser *user = [RKTestUser user]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; operation.delegate = mockDelegate; BOOL success = [operation performMapping:nil]; assertThatBool(success, is(equalToBool(NO))); [mockDelegate verify]; } -- (void)testShouldSetTheErrorWhenMappingOperationFails { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; - RKObjectAttributeMapping* idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; +- (void)testShouldSetTheErrorWhenMappingOperationFails +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; + RKObjectAttributeMapping *idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; [mapping addAttributeMapping:idMapping]; - RKObjectAttributeMapping* nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; + RKObjectAttributeMapping *nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; [mapping addAttributeMapping:nameMapping]; - NSMutableDictionary* dictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"FAILURE", @"id", nil]; - RKTestUser* user = [RKTestUser user]; + NSMutableDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"FAILURE", @"id", nil]; + RKTestUser *user = [RKTestUser user]; id mockObject = [OCMockObject partialMockForObject:user]; [[[mockObject expect] andCall:@selector(fakeValidateValue:forKeyPath:error:) onObject:self] validateValue:[OCMArg anyPointer] forKeyPath:OCMOCK_ANY error:[OCMArg anyPointer]]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:mockObject mapping:mapping]; - NSError* error = nil; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:mockObject mapping:mapping]; + NSError *error = nil; [operation performMapping:&error]; assertThat(error, isNot(nilValue())); [operation release]; @@ -847,34 +897,36 @@ - (void)testShouldSetTheErrorWhenMappingOperationFails { #pragma mark - Attribute Mapping -- (void)testShouldMapAStringToADateAttribute { +- (void)testShouldMapAStringToADateAttribute +{ [RKObjectMapping setDefaultDateFormatters:nil]; - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectAttributeMapping* birthDateMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"birthdate" toKeyPath:@"birthDate"]; + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectAttributeMapping *birthDateMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"birthdate" toKeyPath:@"birthDate"]; [mapping addAttributeMapping:birthDateMapping]; - NSDictionary* dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; - RKTestUser* user = [RKTestUser user]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; - NSError* error = nil; + NSDictionary *dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; + RKTestUser *user = [RKTestUser user]; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + NSError *error = nil; [operation performMapping:&error]; - NSDateFormatter* dateFormatter = [[NSDateFormatter new] autorelease]; + NSDateFormatter *dateFormatter = [[NSDateFormatter new] autorelease]; dateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"]; [dateFormatter setDateFormat:@"MM/dd/yyyy"]; assertThat([dateFormatter stringFromDate:user.birthDate], is(equalTo(@"11/27/1982"))); } -- (void)testShouldMapStringToURL { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectAttributeMapping* websiteMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"website" toKeyPath:@"website"]; +- (void)testShouldMapStringToURL +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectAttributeMapping *websiteMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"website" toKeyPath:@"website"]; [mapping addAttributeMapping:websiteMapping]; - NSDictionary* dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; - RKTestUser* user = [RKTestUser user]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; - NSError* error = nil; + NSDictionary *dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; + RKTestUser *user = [RKTestUser user]; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + NSError *error = nil; [operation performMapping:&error]; assertThat(user.website, isNot(nilValue())); @@ -882,200 +934,213 @@ - (void)testShouldMapStringToURL { assertThat([user.website absoluteString], is(equalTo(@"http://restkit.org/"))); } -- (void)testShouldMapAStringToANumberBool { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectAttributeMapping* websiteMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"is_developer" toKeyPath:@"isDeveloper"]; +- (void)testShouldMapAStringToANumberBool +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectAttributeMapping *websiteMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"is_developer" toKeyPath:@"isDeveloper"]; [mapping addAttributeMapping:websiteMapping]; - NSDictionary* dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; - RKTestUser* user = [RKTestUser user]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; - NSError* error = nil; + NSDictionary *dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; + RKTestUser *user = [RKTestUser user]; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + NSError *error = nil; [operation performMapping:&error]; assertThatBool([[user isDeveloper] boolValue], is(equalToBool(YES))); } -- (void)testShouldMapAShortTrueStringToANumberBool { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectAttributeMapping* websiteMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"is_developer" toKeyPath:@"isDeveloper"]; +- (void)testShouldMapAShortTrueStringToANumberBool +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectAttributeMapping *websiteMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"is_developer" toKeyPath:@"isDeveloper"]; [mapping addAttributeMapping:websiteMapping]; - NSDictionary* dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; - RKTestUser* user = [RKTestUser user]; + NSDictionary *dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; + RKTestUser *user = [RKTestUser user]; [dictionary setValue:@"T" forKey:@"is_developer"]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; - NSError* error = nil; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + NSError *error = nil; [operation performMapping:&error]; assertThatBool([[user isDeveloper] boolValue], is(equalToBool(YES))); } -- (void)testShouldMapAShortFalseStringToANumberBool { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectAttributeMapping* websiteMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"is_developer" toKeyPath:@"isDeveloper"]; +- (void)testShouldMapAShortFalseStringToANumberBool +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectAttributeMapping *websiteMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"is_developer" toKeyPath:@"isDeveloper"]; [mapping addAttributeMapping:websiteMapping]; - NSDictionary* dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; - RKTestUser* user = [RKTestUser user]; + NSDictionary *dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; + RKTestUser *user = [RKTestUser user]; [dictionary setValue:@"f" forKey:@"is_developer"]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; - NSError* error = nil; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + NSError *error = nil; [operation performMapping:&error]; assertThatBool([[user isDeveloper] boolValue], is(equalToBool(NO))); } -- (void)testShouldMapAYesStringToANumberBool { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectAttributeMapping* websiteMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"is_developer" toKeyPath:@"isDeveloper"]; +- (void)testShouldMapAYesStringToANumberBool +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectAttributeMapping *websiteMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"is_developer" toKeyPath:@"isDeveloper"]; [mapping addAttributeMapping:websiteMapping]; - NSDictionary* dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; - RKTestUser* user = [RKTestUser user]; + NSDictionary *dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; + RKTestUser *user = [RKTestUser user]; [dictionary setValue:@"yes" forKey:@"is_developer"]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; - NSError* error = nil; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + NSError *error = nil; [operation performMapping:&error]; assertThatBool([[user isDeveloper] boolValue], is(equalToBool(YES))); } -- (void)testShouldMapANoStringToANumberBool { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectAttributeMapping* websiteMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"is_developer" toKeyPath:@"isDeveloper"]; +- (void)testShouldMapANoStringToANumberBool +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectAttributeMapping *websiteMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"is_developer" toKeyPath:@"isDeveloper"]; [mapping addAttributeMapping:websiteMapping]; - NSDictionary* dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; - RKTestUser* user = [RKTestUser user]; + NSDictionary *dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; + RKTestUser *user = [RKTestUser user]; [dictionary setValue:@"NO" forKey:@"is_developer"]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; - NSError* error = nil; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + NSError *error = nil; [operation performMapping:&error]; assertThatBool([[user isDeveloper] boolValue], is(equalToBool(NO))); } -- (void)testShouldMapAStringToANumber { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectAttributeMapping* websiteMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"lucky_number" toKeyPath:@"luckyNumber"]; +- (void)testShouldMapAStringToANumber +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectAttributeMapping *websiteMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"lucky_number" toKeyPath:@"luckyNumber"]; [mapping addAttributeMapping:websiteMapping]; - NSDictionary* dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; - RKTestUser* user = [RKTestUser user]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; - NSError* error = nil; + NSDictionary *dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; + RKTestUser *user = [RKTestUser user]; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + NSError *error = nil; [operation performMapping:&error]; assertThatInt([user.luckyNumber intValue], is(equalToInt(187))); } -- (void)testShouldMapAStringToADecimalNumber { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectAttributeMapping* websiteMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"weight" toKeyPath:@"weight"]; +- (void)testShouldMapAStringToADecimalNumber +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectAttributeMapping *websiteMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"weight" toKeyPath:@"weight"]; [mapping addAttributeMapping:websiteMapping]; - NSDictionary* dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; - RKTestUser* user = [RKTestUser user]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; - NSError* error = nil; + NSDictionary *dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; + RKTestUser *user = [RKTestUser user]; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + NSError *error = nil; [operation performMapping:&error]; - NSDecimalNumber* weight = user.weight; + NSDecimalNumber *weight = user.weight; assertThatBool([weight isKindOfClass:[NSDecimalNumber class]], is(equalToBool(YES))); assertThatInteger([weight compare:[NSDecimalNumber decimalNumberWithString:@"131.3"]], is(equalToInt(NSOrderedSame))); } -- (void)testShouldMapANumberToAString { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectAttributeMapping* websiteMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"lucky_number" toKeyPath:@"name"]; +- (void)testShouldMapANumberToAString +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectAttributeMapping *websiteMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"lucky_number" toKeyPath:@"name"]; [mapping addAttributeMapping:websiteMapping]; - NSDictionary* dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; - RKTestUser* user = [RKTestUser user]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; - NSError* error = nil; + NSDictionary *dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; + RKTestUser *user = [RKTestUser user]; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + NSError *error = nil; [operation performMapping:&error]; assertThat(user.name, is(equalTo(@"187"))); } -- (void)testShouldMapANumberToANSDecimalNumber { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectAttributeMapping* websiteMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"lucky_number" toKeyPath:@"weight"]; +- (void)testShouldMapANumberToANSDecimalNumber +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectAttributeMapping *websiteMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"lucky_number" toKeyPath:@"weight"]; [mapping addAttributeMapping:websiteMapping]; - NSDictionary* dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; - RKTestUser* user = [RKTestUser user]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; - NSError* error = nil; + NSDictionary *dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; + RKTestUser *user = [RKTestUser user]; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + NSError *error = nil; [operation performMapping:&error]; - NSDecimalNumber* weight = user.weight; + NSDecimalNumber *weight = user.weight; assertThatBool([weight isKindOfClass:[NSDecimalNumber class]], is(equalToBool(YES))); assertThatInteger([weight compare:[NSDecimalNumber decimalNumberWithString:@"187"]], is(equalToInt(NSOrderedSame))); } -- (void)testShouldMapANumberToADate { - NSDateFormatter* dateFormatter = [[NSDateFormatter new] autorelease]; +- (void)testShouldMapANumberToADate +{ + NSDateFormatter *dateFormatter = [[NSDateFormatter new] autorelease]; [dateFormatter setDateFormat:@"MM/dd/yyyy"]; - NSDate* date = [dateFormatter dateFromString:@"11/27/1982"]; + NSDate *date = [dateFormatter dateFromString:@"11/27/1982"]; - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectAttributeMapping* birthDateMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"dateAsNumber" toKeyPath:@"birthDate"]; + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectAttributeMapping *birthDateMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"dateAsNumber" toKeyPath:@"birthDate"]; [mapping addAttributeMapping:birthDateMapping]; - NSMutableDictionary* dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; + NSMutableDictionary *dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; [dictionary setValue:[NSNumber numberWithInt:[date timeIntervalSince1970]] forKey:@"dateAsNumber"]; - RKTestUser* user = [RKTestUser user]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; - NSError* error = nil; + RKTestUser *user = [RKTestUser user]; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + NSError *error = nil; [operation performMapping:&error]; assertThat([dateFormatter stringFromDate:user.birthDate], is(equalTo(@"11/27/1982"))); } -- (void)testShouldMapANestedKeyPathToAnAttribute { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectAttributeMapping* countryMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"address.country" toKeyPath:@"country"]; +- (void)testShouldMapANestedKeyPathToAnAttribute +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectAttributeMapping *countryMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"address.country" toKeyPath:@"country"]; [mapping addAttributeMapping:countryMapping]; - NSDictionary* dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; - RKTestUser* user = [RKTestUser user]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; - NSError* error = nil; + NSDictionary *dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; + RKTestUser *user = [RKTestUser user]; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + NSError *error = nil; [operation performMapping:&error]; assertThat(user.country, is(equalTo(@"USA"))); } -- (void)testShouldMapANestedArrayOfStringsToAnAttribute { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectAttributeMapping* countryMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"interests" toKeyPath:@"interests"]; +- (void)testShouldMapANestedArrayOfStringsToAnAttribute +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectAttributeMapping *countryMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"interests" toKeyPath:@"interests"]; [mapping addAttributeMapping:countryMapping]; - NSDictionary* dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; - RKTestUser* user = [RKTestUser user]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; - NSError* error = nil; + NSDictionary *dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; + RKTestUser *user = [RKTestUser user]; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + NSError *error = nil; [operation performMapping:&error]; - NSArray* interests = [NSArray arrayWithObjects:@"Hacking", @"Running", nil]; + NSArray *interests = [NSArray arrayWithObjects:@"Hacking", @"Running", nil]; assertThat(user.interests, is(equalTo(interests))); } -- (void)testShouldMapANestedDictionaryToAnAttribute { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectAttributeMapping* countryMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"address" toKeyPath:@"addressDictionary"]; +- (void)testShouldMapANestedDictionaryToAnAttribute +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectAttributeMapping *countryMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"address" toKeyPath:@"addressDictionary"]; [mapping addAttributeMapping:countryMapping]; - NSDictionary* dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; - RKTestUser* user = [RKTestUser user]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; - NSError* error = nil; + NSDictionary *dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; + RKTestUser *user = [RKTestUser user]; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + NSError *error = nil; [operation performMapping:&error]; - NSDictionary* address = [NSDictionary dictionaryWithKeysAndObjects: + NSDictionary *address = [NSDictionary dictionaryWithKeysAndObjects: @"city", @"Carrboro", @"state", @"North Carolina", @"id", [NSNumber numberWithInt:1234], @@ -1083,148 +1148,156 @@ - (void)testShouldMapANestedDictionaryToAnAttribute { assertThat(user.addressDictionary, is(equalTo(address))); } -- (void)testShouldNotSetAPropertyWhenTheValueIsTheSame { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectAttributeMapping* nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; +- (void)testShouldNotSetAPropertyWhenTheValueIsTheSame +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectAttributeMapping *nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; [mapping addAttributeMapping:nameMapping]; - NSDictionary* dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; - RKTestUser* user = [RKTestUser user]; + NSDictionary *dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; + RKTestUser *user = [RKTestUser user]; user.name = @"Blake Watters"; id mockUser = [OCMockObject partialMockForObject:user]; [[mockUser reject] setName:OCMOCK_ANY]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; - NSError* error = nil; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + NSError *error = nil; [operation performMapping:&error]; } -- (void)testShouldNotSetTheDestinationPropertyWhenBothAreNil { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectAttributeMapping* nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; +- (void)testShouldNotSetTheDestinationPropertyWhenBothAreNil +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectAttributeMapping *nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; [mapping addAttributeMapping:nameMapping]; - NSMutableDictionary* dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; + NSMutableDictionary *dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; [dictionary setValue:[NSNull null] forKey:@"name"]; - RKTestUser* user = [RKTestUser user]; + RKTestUser *user = [RKTestUser user]; user.name = nil; id mockUser = [OCMockObject partialMockForObject:user]; [[mockUser reject] setName:OCMOCK_ANY]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; - NSError* error = nil; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + NSError *error = nil; [operation performMapping:&error]; } -- (void)testShouldSetNilForNSNullValues { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectAttributeMapping* nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; +- (void)testShouldSetNilForNSNullValues +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectAttributeMapping *nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; [mapping addAttributeMapping:nameMapping]; - NSDictionary* dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; + NSDictionary *dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; [dictionary setValue:[NSNull null] forKey:@"name"]; - RKTestUser* user = [RKTestUser user]; + RKTestUser *user = [RKTestUser user]; user.name = @"Blake Watters"; id mockUser = [OCMockObject partialMockForObject:user]; [[mockUser expect] setName:nil]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; - NSError* error = nil; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + NSError *error = nil; [operation performMapping:&error]; [mockUser verify]; } -- (void)testDelegateIsInformedWhenANilValueIsMappedForNSNullWithExistingValue { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectAttributeMapping* nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; +- (void)testDelegateIsInformedWhenANilValueIsMappedForNSNullWithExistingValue +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectAttributeMapping *nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; [mapping addAttributeMapping:nameMapping]; - NSDictionary* dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; + NSDictionary *dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; [dictionary setValue:[NSNull null] forKey:@"name"]; - RKTestUser* user = [RKTestUser user]; + RKTestUser *user = [RKTestUser user]; user.name = @"Blake Watters"; id mockDelegate = [OCMockObject mockForProtocol:@protocol(RKObjectMappingOperationDelegate)]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; operation.delegate = mockDelegate; - NSError* error = nil; + NSError *error = nil; [[mockDelegate expect] objectMappingOperation:operation didFindMapping:nameMapping forKeyPath:@"name"]; [[mockDelegate expect] objectMappingOperation:operation didSetValue:nil forKeyPath:@"name" usingMapping:nameMapping]; [operation performMapping:&error]; [mockDelegate verify]; } -- (void)testDelegateIsInformedWhenUnchangedValueIsSkipped { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectAttributeMapping* nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; +- (void)testDelegateIsInformedWhenUnchangedValueIsSkipped +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectAttributeMapping *nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; [mapping addAttributeMapping:nameMapping]; - NSDictionary* dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; + NSDictionary *dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; [dictionary setValue:@"Blake Watters" forKey:@"name"]; - RKTestUser* user = [RKTestUser user]; + RKTestUser *user = [RKTestUser user]; user.name = @"Blake Watters"; id mockDelegate = [OCMockObject mockForProtocol:@protocol(RKObjectMappingOperationDelegate)]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; operation.delegate = mockDelegate; - NSError* error = nil; + NSError *error = nil; [[mockDelegate expect] objectMappingOperation:operation didFindMapping:nameMapping forKeyPath:@"name"]; [[mockDelegate expect] objectMappingOperation:operation didNotSetUnchangedValue:@"Blake Watters" forKeyPath:@"name" usingMapping:nameMapping]; [operation performMapping:&error]; [mockDelegate verify]; } -- (void)testShouldOptionallySetDefaultValueForAMissingKeyPath { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectAttributeMapping* nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; +- (void)testShouldOptionallySetDefaultValueForAMissingKeyPath +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectAttributeMapping *nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; [mapping addAttributeMapping:nameMapping]; - NSMutableDictionary* dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; + NSMutableDictionary *dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; [dictionary removeObjectForKey:@"name"]; - RKTestUser* user = [RKTestUser user]; + RKTestUser *user = [RKTestUser user]; user.name = @"Blake Watters"; id mockUser = [OCMockObject partialMockForObject:user]; [[mockUser expect] setName:nil]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; id mockMapping = [OCMockObject partialMockForObject:mapping]; BOOL returnValue = YES; [[[mockMapping expect] andReturnValue:OCMOCK_VALUE(returnValue)] shouldSetDefaultValueForMissingAttributes]; - NSError* error = nil; + NSError *error = nil; [operation performMapping:&error]; [mockUser verify]; } -- (void)testShouldOptionallyIgnoreAMissingSourceKeyPath { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectAttributeMapping* nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; +- (void)testShouldOptionallyIgnoreAMissingSourceKeyPath +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectAttributeMapping *nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; [mapping addAttributeMapping:nameMapping]; - NSMutableDictionary* dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; + NSMutableDictionary *dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; [dictionary removeObjectForKey:@"name"]; - RKTestUser* user = [RKTestUser user]; + RKTestUser *user = [RKTestUser user]; user.name = @"Blake Watters"; id mockUser = [OCMockObject partialMockForObject:user]; [[mockUser reject] setName:nil]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:user mapping:mapping]; id mockMapping = [OCMockObject partialMockForObject:mapping]; BOOL returnValue = NO; [[[mockMapping expect] andReturnValue:OCMOCK_VALUE(returnValue)] shouldSetDefaultValueForMissingAttributes]; - NSError* error = nil; + NSError *error = nil; [operation performMapping:&error]; assertThat(user.name, is(equalTo(@"Blake Watters"))); } #pragma mark - Relationship Mapping -- (void)testShouldMapANestedObject { - RKObjectMapping* userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectAttributeMapping* nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; +- (void)testShouldMapANestedObject +{ + RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectAttributeMapping *nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; [userMapping addAttributeMapping:nameMapping]; - RKObjectMapping* addressMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; - RKObjectAttributeMapping* cityMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"city" toKeyPath:@"city"]; + RKObjectMapping *addressMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; + RKObjectAttributeMapping *cityMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"city" toKeyPath:@"city"]; [addressMapping addAttributeMapping:cityMapping]; - RKObjectRelationshipMapping* hasOneMapping = [RKObjectRelationshipMapping mappingFromKeyPath:@"address" toKeyPath:@"address" withMapping:addressMapping]; + RKObjectRelationshipMapping *hasOneMapping = [RKObjectRelationshipMapping mappingFromKeyPath:@"address" toKeyPath:@"address" withMapping:addressMapping]; [userMapping addRelationshipMapping:hasOneMapping]; - RKObjectMapper* mapper = [RKObjectMapper new]; + RKObjectMapper *mapper = [RKObjectMapper new]; id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; - RKTestUser* user = [RKTestUser user]; + RKTestUser *user = [RKTestUser user]; BOOL success = [mapper mapFromObject:userInfo toObject:user atKeyPath:@"" usingMapping:userMapping]; [mapper release]; assertThatBool(success, is(equalToBool(YES))); @@ -1232,20 +1305,21 @@ - (void)testShouldMapANestedObject { assertThat(user.address, isNot(nilValue())); } -- (void)testShouldMapANestedObjectToCollection { - RKObjectMapping* userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectAttributeMapping* nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; +- (void)testShouldMapANestedObjectToCollection +{ + RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectAttributeMapping *nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; [userMapping addAttributeMapping:nameMapping]; - RKObjectMapping* addressMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; - RKObjectAttributeMapping* cityMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"city" toKeyPath:@"city"]; + RKObjectMapping *addressMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; + RKObjectAttributeMapping *cityMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"city" toKeyPath:@"city"]; [addressMapping addAttributeMapping:cityMapping]; - RKObjectRelationshipMapping* hasOneMapping = [RKObjectRelationshipMapping mappingFromKeyPath:@"address" toKeyPath:@"friends" withMapping:addressMapping]; + RKObjectRelationshipMapping *hasOneMapping = [RKObjectRelationshipMapping mappingFromKeyPath:@"address" toKeyPath:@"friends" withMapping:addressMapping]; [userMapping addRelationshipMapping:hasOneMapping]; - RKObjectMapper* mapper = [RKObjectMapper new]; + RKObjectMapper *mapper = [RKObjectMapper new]; id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; - RKTestUser* user = [RKTestUser user]; + RKTestUser *user = [RKTestUser user]; BOOL success = [mapper mapFromObject:userInfo toObject:user atKeyPath:@"" usingMapping:userMapping]; [mapper release]; assertThatBool(success, is(equalToBool(YES))); @@ -1254,20 +1328,21 @@ - (void)testShouldMapANestedObjectToCollection { assertThatUnsignedInteger([user.friends count], is(equalToInt(1))); } -- (void)testShouldMapANestedObjectToOrderedSetCollection { - RKObjectMapping* userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectAttributeMapping* nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; +- (void)testShouldMapANestedObjectToOrderedSetCollection +{ + RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectAttributeMapping *nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; [userMapping addAttributeMapping:nameMapping]; - RKObjectMapping* addressMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; - RKObjectAttributeMapping* cityMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"city" toKeyPath:@"city"]; + RKObjectMapping *addressMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; + RKObjectAttributeMapping *cityMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"city" toKeyPath:@"city"]; [addressMapping addAttributeMapping:cityMapping]; - RKObjectRelationshipMapping* hasOneMapping = [RKObjectRelationshipMapping mappingFromKeyPath:@"address" toKeyPath:@"friendsOrderedSet" withMapping:addressMapping]; + RKObjectRelationshipMapping *hasOneMapping = [RKObjectRelationshipMapping mappingFromKeyPath:@"address" toKeyPath:@"friendsOrderedSet" withMapping:addressMapping]; [userMapping addRelationshipMapping:hasOneMapping]; - RKObjectMapper* mapper = [RKObjectMapper new]; + RKObjectMapper *mapper = [RKObjectMapper new]; id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; - RKTestUser* user = [RKTestUser user]; + RKTestUser *user = [RKTestUser user]; BOOL success = [mapper mapFromObject:userInfo toObject:user atKeyPath:@"" usingMapping:userMapping]; [mapper release]; assertThatBool(success, is(equalToBool(YES))); @@ -1276,38 +1351,40 @@ - (void)testShouldMapANestedObjectToOrderedSetCollection { assertThatUnsignedInteger([user.friendsOrderedSet count], is(equalToInt(1))); } -- (void)testShouldMapANestedObjectCollection { - RKObjectMapping* userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectAttributeMapping* nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; +- (void)testShouldMapANestedObjectCollection +{ + RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectAttributeMapping *nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; [userMapping addAttributeMapping:nameMapping]; - RKObjectRelationshipMapping* hasManyMapping = [RKObjectRelationshipMapping mappingFromKeyPath:@"friends" toKeyPath:@"friends" withMapping:userMapping]; + RKObjectRelationshipMapping *hasManyMapping = [RKObjectRelationshipMapping mappingFromKeyPath:@"friends" toKeyPath:@"friends" withMapping:userMapping]; [userMapping addRelationshipMapping:hasManyMapping]; - RKObjectMapper* mapper = [RKObjectMapper new]; + RKObjectMapper *mapper = [RKObjectMapper new]; id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; - RKTestUser* user = [RKTestUser user]; + RKTestUser *user = [RKTestUser user]; BOOL success = [mapper mapFromObject:userInfo toObject:user atKeyPath:@"" usingMapping:userMapping]; [mapper release]; assertThatBool(success, is(equalToBool(YES))); assertThat(user.name, is(equalTo(@"Blake Watters"))); assertThat(user.friends, isNot(nilValue())); assertThatUnsignedInteger([user.friends count], is(equalToInt(2))); - NSArray* names = [NSArray arrayWithObjects:@"Jeremy Ellison", @"Rachit Shukla", nil]; + NSArray *names = [NSArray arrayWithObjects:@"Jeremy Ellison", @"Rachit Shukla", nil]; assertThat([user.friends valueForKey:@"name"], is(equalTo(names))); } -- (void)testShouldMapANestedArrayIntoASet { - RKObjectMapping* userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectAttributeMapping* nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; +- (void)testShouldMapANestedArrayIntoASet +{ + RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectAttributeMapping *nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; [userMapping addAttributeMapping:nameMapping]; - RKObjectRelationshipMapping* hasManyMapping = [RKObjectRelationshipMapping mappingFromKeyPath:@"friends" toKeyPath:@"friendsSet" withMapping:userMapping]; + RKObjectRelationshipMapping *hasManyMapping = [RKObjectRelationshipMapping mappingFromKeyPath:@"friends" toKeyPath:@"friendsSet" withMapping:userMapping]; [userMapping addRelationshipMapping:hasManyMapping]; - RKObjectMapper* mapper = [RKObjectMapper new]; + RKObjectMapper *mapper = [RKObjectMapper new]; id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; - RKTestUser* user = [RKTestUser user]; + RKTestUser *user = [RKTestUser user]; BOOL success = [mapper mapFromObject:userInfo toObject:user atKeyPath:@"" usingMapping:userMapping]; [mapper release]; assertThatBool(success, is(equalToBool(YES))); @@ -1315,21 +1392,22 @@ - (void)testShouldMapANestedArrayIntoASet { assertThat(user.friendsSet, isNot(nilValue())); assertThatBool([user.friendsSet isKindOfClass:[NSSet class]], is(equalToBool(YES))); assertThatUnsignedInteger([user.friendsSet count], is(equalToInt(2))); - NSSet* names = [NSSet setWithObjects:@"Jeremy Ellison", @"Rachit Shukla", nil]; + NSSet *names = [NSSet setWithObjects:@"Jeremy Ellison", @"Rachit Shukla", nil]; assertThat([user.friendsSet valueForKey:@"name"], is(equalTo(names))); } -- (void)testShouldMapANestedArrayIntoAnOrderedSet { - RKObjectMapping* userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectAttributeMapping* nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; +- (void)testShouldMapANestedArrayIntoAnOrderedSet +{ + RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectAttributeMapping *nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; [userMapping addAttributeMapping:nameMapping]; - RKObjectRelationshipMapping* hasManyMapping = [RKObjectRelationshipMapping mappingFromKeyPath:@"friends" toKeyPath:@"friendsOrderedSet" withMapping:userMapping]; + RKObjectRelationshipMapping *hasManyMapping = [RKObjectRelationshipMapping mappingFromKeyPath:@"friends" toKeyPath:@"friendsOrderedSet" withMapping:userMapping]; [userMapping addRelationshipMapping:hasManyMapping]; - RKObjectMapper* mapper = [RKObjectMapper new]; + RKObjectMapper *mapper = [RKObjectMapper new]; id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; - RKTestUser* user = [RKTestUser user]; + RKTestUser *user = [RKTestUser user]; BOOL success = [mapper mapFromObject:userInfo toObject:user atKeyPath:@"" usingMapping:userMapping]; [mapper release]; assertThatBool(success, is(equalToBool(YES))); @@ -1341,46 +1419,48 @@ - (void)testShouldMapANestedArrayIntoAnOrderedSet { assertThat([user.friendsOrderedSet valueForKey:@"name"], is(equalTo(names))); } -- (void)testShouldNotSetThePropertyWhenTheNestedObjectIsIdentical { - RKTestUser* user = [RKTestUser user]; - RKTestAddress* address = [RKTestAddress address]; +- (void)testShouldNotSetThePropertyWhenTheNestedObjectIsIdentical +{ + RKTestUser *user = [RKTestUser user]; + RKTestAddress *address = [RKTestAddress address]; address.addressID = [NSNumber numberWithInt:1234]; user.address = address; id mockUser = [OCMockObject partialMockForObject:user]; [[mockUser reject] setAddress:OCMOCK_ANY]; - RKObjectMapping* userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectAttributeMapping* nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; + RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectAttributeMapping *nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; [userMapping addAttributeMapping:nameMapping]; - RKObjectMapping* addressMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; - RKObjectAttributeMapping* idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"addressID"]; + RKObjectMapping *addressMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; + RKObjectAttributeMapping *idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"addressID"]; [addressMapping addAttributeMapping:idMapping]; - RKObjectRelationshipMapping* hasOneMapping = [RKObjectRelationshipMapping mappingFromKeyPath:@"address" toKeyPath:@"address" withMapping:addressMapping]; + RKObjectRelationshipMapping *hasOneMapping = [RKObjectRelationshipMapping mappingFromKeyPath:@"address" toKeyPath:@"address" withMapping:addressMapping]; [userMapping addRelationshipMapping:hasOneMapping]; - RKObjectMapper* mapper = [RKObjectMapper new]; + RKObjectMapper *mapper = [RKObjectMapper new]; id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; [mapper mapFromObject:userInfo toObject:user atKeyPath:@"" usingMapping:userMapping]; [mapper release]; } -- (void)testSkippingOfIdenticalObjectsInformsDelegate { - RKTestUser* user = [RKTestUser user]; - RKTestAddress* address = [RKTestAddress address]; +- (void)testSkippingOfIdenticalObjectsInformsDelegate +{ + RKTestUser *user = [RKTestUser user]; + RKTestAddress *address = [RKTestAddress address]; address.addressID = [NSNumber numberWithInt:1234]; user.address = address; id mockUser = [OCMockObject partialMockForObject:user]; [[mockUser reject] setAddress:OCMOCK_ANY]; - RKObjectMapping* userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectAttributeMapping* nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; + RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectAttributeMapping *nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; [userMapping addAttributeMapping:nameMapping]; - RKObjectMapping* addressMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; - RKObjectAttributeMapping* idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"addressID"]; + RKObjectMapping *addressMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; + RKObjectAttributeMapping *idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"addressID"]; [addressMapping addAttributeMapping:idMapping]; - RKObjectRelationshipMapping* hasOneMapping = [RKObjectRelationshipMapping mappingFromKeyPath:@"address" toKeyPath:@"address" withMapping:addressMapping]; + RKObjectRelationshipMapping *hasOneMapping = [RKObjectRelationshipMapping mappingFromKeyPath:@"address" toKeyPath:@"address" withMapping:addressMapping]; [userMapping addRelationshipMapping:hasOneMapping]; id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; @@ -1392,25 +1472,26 @@ - (void)testSkippingOfIdenticalObjectsInformsDelegate { [mockDelegate verify]; } -- (void)testShouldNotSetThePropertyWhenTheNestedObjectCollectionIsIdentical { - RKObjectMapping* userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectAttributeMapping* idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; - RKObjectAttributeMapping* nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; +- (void)testShouldNotSetThePropertyWhenTheNestedObjectCollectionIsIdentical +{ + RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectAttributeMapping *idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"userID"]; + RKObjectAttributeMapping *nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; [userMapping addAttributeMapping:idMapping]; [userMapping addAttributeMapping:nameMapping]; - RKObjectRelationshipMapping* hasManyMapping = [RKObjectRelationshipMapping mappingFromKeyPath:@"friends" toKeyPath:@"friends" withMapping:userMapping]; + RKObjectRelationshipMapping *hasManyMapping = [RKObjectRelationshipMapping mappingFromKeyPath:@"friends" toKeyPath:@"friends" withMapping:userMapping]; [userMapping addRelationshipMapping:hasManyMapping]; - RKObjectMapper* mapper = [RKObjectMapper new]; + RKObjectMapper *mapper = [RKObjectMapper new]; id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; - RKTestUser* user = [RKTestUser user]; + RKTestUser *user = [RKTestUser user]; // Set the friends up - RKTestUser* jeremy = [RKTestUser user]; + RKTestUser *jeremy = [RKTestUser user]; jeremy.name = @"Jeremy Ellison"; jeremy.userID = [NSNumber numberWithInt:187]; - RKTestUser* rachit = [RKTestUser user]; + RKTestUser *rachit = [RKTestUser user]; rachit.name = @"Rachit Shukla"; rachit.userID = [NSNumber numberWithInt:7]; user.friends = [NSArray arrayWithObjects:jeremy, rachit, nil]; @@ -1422,67 +1503,70 @@ - (void)testShouldNotSetThePropertyWhenTheNestedObjectCollectionIsIdentical { [mockUser verify]; } -- (void)testShouldOptionallyNilOutTheRelationshipIfItIsMissing { - RKTestUser* user = [RKTestUser user]; - RKTestAddress* address = [RKTestAddress address]; +- (void)testShouldOptionallyNilOutTheRelationshipIfItIsMissing +{ + RKTestUser *user = [RKTestUser user]; + RKTestAddress *address = [RKTestAddress address]; address.addressID = [NSNumber numberWithInt:1234]; user.address = address; id mockUser = [OCMockObject partialMockForObject:user]; [[mockUser expect] setAddress:nil]; - RKObjectMapping* userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectAttributeMapping* nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; + RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectAttributeMapping *nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; [userMapping addAttributeMapping:nameMapping]; - RKObjectMapping* addressMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; - RKObjectAttributeMapping* idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"addressID"]; + RKObjectMapping *addressMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; + RKObjectAttributeMapping *idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"addressID"]; [addressMapping addAttributeMapping:idMapping]; - RKObjectRelationshipMapping* relationshipMapping = [RKObjectRelationshipMapping mappingFromKeyPath:@"address" toKeyPath:@"address" withMapping:addressMapping]; + RKObjectRelationshipMapping *relationshipMapping = [RKObjectRelationshipMapping mappingFromKeyPath:@"address" toKeyPath:@"address" withMapping:addressMapping]; [userMapping addRelationshipMapping:relationshipMapping]; - NSMutableDictionary* dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; + NSMutableDictionary *dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; [dictionary removeObjectForKey:@"address"]; id mockMapping = [OCMockObject partialMockForObject:userMapping]; BOOL returnValue = YES; [[[mockMapping expect] andReturnValue:OCMOCK_VALUE(returnValue)] setNilForMissingRelationships]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:mockUser mapping:mockMapping]; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:mockUser mapping:mockMapping]; - NSError* error = nil; + NSError *error = nil; [operation performMapping:&error]; [mockUser verify]; } -- (void)testShouldNotNilOutTheRelationshipIfItIsMissingAndCurrentlyNilOnTheTargetObject { - RKTestUser* user = [RKTestUser user]; +- (void)testShouldNotNilOutTheRelationshipIfItIsMissingAndCurrentlyNilOnTheTargetObject +{ + RKTestUser *user = [RKTestUser user]; user.address = nil; id mockUser = [OCMockObject partialMockForObject:user]; [[mockUser reject] setAddress:nil]; - RKObjectMapping* userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectAttributeMapping* nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; + RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectAttributeMapping *nameMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"name" toKeyPath:@"name"]; [userMapping addAttributeMapping:nameMapping]; - RKObjectMapping* addressMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; - RKObjectAttributeMapping* idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"addressID"]; + RKObjectMapping *addressMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; + RKObjectAttributeMapping *idMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"id" toKeyPath:@"addressID"]; [addressMapping addAttributeMapping:idMapping]; - RKObjectRelationshipMapping* relationshipMapping = [RKObjectRelationshipMapping mappingFromKeyPath:@"address" toKeyPath:@"address" withMapping:addressMapping]; + RKObjectRelationshipMapping *relationshipMapping = [RKObjectRelationshipMapping mappingFromKeyPath:@"address" toKeyPath:@"address" withMapping:addressMapping]; [userMapping addRelationshipMapping:relationshipMapping]; - NSMutableDictionary* dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; + NSMutableDictionary *dictionary = [[RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"] mutableCopy]; [dictionary removeObjectForKey:@"address"]; id mockMapping = [OCMockObject partialMockForObject:userMapping]; BOOL returnValue = YES; [[[mockMapping expect] andReturnValue:OCMOCK_VALUE(returnValue)] setNilForMissingRelationships]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:mockUser mapping:mockMapping]; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:mockUser mapping:mockMapping]; - NSError* error = nil; + NSError *error = nil; [operation performMapping:&error]; [mockUser verify]; } #pragma mark - RKObjectMappingProvider -- (void)testShouldRegisterRailsIdiomaticObjects { - RKObjectManager* objectManager = [RKTestFactory objectManager]; - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; +- (void)testShouldRegisterRailsIdiomaticObjects +{ + RKObjectManager *objectManager = [RKTestFactory objectManager]; + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; [mapping mapAttributes:@"name", @"website", nil]; [mapping mapKeyPath:@"id" toAttribute:@"userID"]; @@ -1490,10 +1574,10 @@ - (void)testShouldRegisterRailsIdiomaticObjects { [objectManager.router routeClass:[RKTestUser class] toResourcePath:@"/humans" forMethod:RKRequestMethodPOST]; [objectManager.mappingProvider registerMapping:mapping withRootKeyPath:@"human"]; - RKTestUser* user = [RKTestUser new]; + RKTestUser *user = [RKTestUser new]; user.userID = [NSNumber numberWithInt:1]; - RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; + RKTestResponseLoader *loader = [RKTestResponseLoader responseLoader]; loader.timeout = 5; [objectManager getObject:user delegate:loader]; [loader waitForResponse]; @@ -1507,37 +1591,39 @@ - (void)testShouldRegisterRailsIdiomaticObjects { assertThat(user.website, is(equalTo([NSURL URLWithString:@"http://restkit.org/"]))); } -- (void)testShouldReturnAllMappingsForAClass { - RKObjectMapping* firstMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectMapping* secondMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectMapping* thirdMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectMappingProvider* mappingProvider = [[RKObjectMappingProvider new] autorelease]; +- (void)testShouldReturnAllMappingsForAClass +{ + RKObjectMapping *firstMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectMapping *secondMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectMapping *thirdMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectMappingProvider *mappingProvider = [[RKObjectMappingProvider new] autorelease]; [mappingProvider addObjectMapping:firstMapping]; [mappingProvider addObjectMapping:secondMapping]; [mappingProvider setMapping:thirdMapping forKeyPath:@"third"]; assertThat([mappingProvider objectMappingsForClass:[RKTestUser class]], is(equalTo([NSArray arrayWithObjects:firstMapping, secondMapping, thirdMapping, nil]))); } -- (void)testShouldReturnAllMappingsForAClassAndNotExplodeWithRegisteredDynamicMappings { - RKObjectMappingProvider* provider = [[RKObjectMappingProvider new] autorelease]; - RKObjectMapping* boyMapping = [RKObjectMapping mappingForClass:[Boy class]]; +- (void)testShouldReturnAllMappingsForAClassAndNotExplodeWithRegisteredDynamicMappings +{ + RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; + RKObjectMapping *boyMapping = [RKObjectMapping mappingForClass:[Boy class]]; [boyMapping mapAttributes:@"name", nil]; - RKObjectMapping* girlMapping = [RKObjectMapping mappingForClass:[Girl class]]; + RKObjectMapping *girlMapping = [RKObjectMapping mappingForClass:[Girl class]]; [girlMapping mapAttributes:@"name", nil]; - RKDynamicObjectMapping* dynamicMapping = [RKDynamicObjectMapping dynamicMapping]; + RKDynamicObjectMapping *dynamicMapping = [RKDynamicObjectMapping dynamicMapping]; [dynamicMapping setObjectMapping:boyMapping whenValueOfKeyPath:@"type" isEqualTo:@"Boy"]; [dynamicMapping setObjectMapping:girlMapping whenValueOfKeyPath:@"type" isEqualTo:@"Girl"]; [provider setMapping:dynamicMapping forKeyPath:@"dynamic"]; - RKObjectMapping* firstMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectMapping* secondMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectMapping *firstMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectMapping *secondMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; [provider addObjectMapping:firstMapping]; [provider setMapping:secondMapping forKeyPath:@"second"]; - NSException* exception = nil; + NSException *exception = nil; NSArray *actualMappings = nil; @try { actualMappings = [provider objectMappingsForClass:[RKTestUser class]]; } - @catch (NSException * e) { + @catch (NSException *e) { exception = e; } assertThat(exception, is(nilValue())); @@ -1546,13 +1632,14 @@ - (void)testShouldReturnAllMappingsForAClassAndNotExplodeWithRegisteredDynamicMa #pragma mark - RKDynamicObjectMapping -- (void)testShouldMapASingleObjectDynamically { - RKObjectMapping* boyMapping = [RKObjectMapping mappingForClass:[Boy class]]; +- (void)testShouldMapASingleObjectDynamically +{ + RKObjectMapping *boyMapping = [RKObjectMapping mappingForClass:[Boy class]]; [boyMapping mapAttributes:@"name", nil]; - RKObjectMapping* girlMapping = [RKObjectMapping mappingForClass:[Girl class]]; + RKObjectMapping *girlMapping = [RKObjectMapping mappingForClass:[Girl class]]; [girlMapping mapAttributes:@"name", nil]; - RKDynamicObjectMapping* dynamicMapping = [RKDynamicObjectMapping dynamicMapping]; - dynamicMapping.objectMappingForDataBlock = ^ RKObjectMapping* (id mappableData) { + RKDynamicObjectMapping *dynamicMapping = [RKDynamicObjectMapping dynamicMapping]; + dynamicMapping.objectMappingForDataBlock = ^ RKObjectMapping *(id mappableData) { if ([[mappableData valueForKey:@"type"] isEqualToString:@"Boy"]) { return boyMapping; } else if ([[mappableData valueForKey:@"type"] isEqualToString:@"Girl"]) { @@ -1562,97 +1649,101 @@ - (void)testShouldMapASingleObjectDynamically { return nil; }; - RKObjectMappingProvider* provider = [[RKObjectMappingProvider new] autorelease]; + RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; [provider setMapping:dynamicMapping forKeyPath:@""]; id mockProvider = [OCMockObject partialMockForObject:provider]; id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"boy.json"]; - RKObjectMapper* mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:mockProvider]; - Boy* user = [[mapper performMapping] asObject]; + RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:mockProvider]; + Boy *user = [[mapper performMapping] asObject]; assertThat(user, is(instanceOf([Boy class]))); assertThat(user.name, is(equalTo(@"Blake Watters"))); } -- (void)testShouldMapASingleObjectDynamicallyWithADeclarativeMatcher { - RKObjectMapping* boyMapping = [RKObjectMapping mappingForClass:[Boy class]]; +- (void)testShouldMapASingleObjectDynamicallyWithADeclarativeMatcher +{ + RKObjectMapping *boyMapping = [RKObjectMapping mappingForClass:[Boy class]]; [boyMapping mapAttributes:@"name", nil]; - RKObjectMapping* girlMapping = [RKObjectMapping mappingForClass:[Girl class]]; + RKObjectMapping *girlMapping = [RKObjectMapping mappingForClass:[Girl class]]; [girlMapping mapAttributes:@"name", nil]; - RKDynamicObjectMapping* dynamicMapping = [RKDynamicObjectMapping dynamicMapping]; + RKDynamicObjectMapping *dynamicMapping = [RKDynamicObjectMapping dynamicMapping]; [dynamicMapping setObjectMapping:boyMapping whenValueOfKeyPath:@"type" isEqualTo:@"Boy"]; [dynamicMapping setObjectMapping:girlMapping whenValueOfKeyPath:@"type" isEqualTo:@"Girl"]; - RKObjectMappingProvider* provider = [[RKObjectMappingProvider new] autorelease]; + RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; [provider setMapping:dynamicMapping forKeyPath:@""]; id mockProvider = [OCMockObject partialMockForObject:provider]; id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"boy.json"]; - RKObjectMapper* mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:mockProvider]; - Boy* user = [[mapper performMapping] asObject]; + RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:mockProvider]; + Boy *user = [[mapper performMapping] asObject]; assertThat(user, is(instanceOf([Boy class]))); assertThat(user.name, is(equalTo(@"Blake Watters"))); } -- (void)testShouldACollectionOfObjectsDynamically { - RKObjectMapping* boyMapping = [RKObjectMapping mappingForClass:[Boy class]]; +- (void)testShouldACollectionOfObjectsDynamically +{ + RKObjectMapping *boyMapping = [RKObjectMapping mappingForClass:[Boy class]]; [boyMapping mapAttributes:@"name", nil]; - RKObjectMapping* girlMapping = [RKObjectMapping mappingForClass:[Girl class]]; + RKObjectMapping *girlMapping = [RKObjectMapping mappingForClass:[Girl class]]; [girlMapping mapAttributes:@"name", nil]; - RKDynamicObjectMapping* dynamicMapping = [RKDynamicObjectMapping dynamicMapping]; + RKDynamicObjectMapping *dynamicMapping = [RKDynamicObjectMapping dynamicMapping]; [dynamicMapping setObjectMapping:boyMapping whenValueOfKeyPath:@"type" isEqualTo:@"Boy"]; [dynamicMapping setObjectMapping:girlMapping whenValueOfKeyPath:@"type" isEqualTo:@"Girl"]; - RKObjectMappingProvider* provider = [[RKObjectMappingProvider new] autorelease]; + RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; [provider setMapping:dynamicMapping forKeyPath:@""]; id mockProvider = [OCMockObject partialMockForObject:provider]; id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"mixed.json"]; - RKObjectMapper* mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:mockProvider]; - NSArray* objects = [[mapper performMapping] asCollection]; + RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:mockProvider]; + NSArray *objects = [[mapper performMapping] asCollection]; assertThat(objects, hasCountOf(2)); assertThat([objects objectAtIndex:0], is(instanceOf([Boy class]))); assertThat([objects objectAtIndex:1], is(instanceOf([Girl class]))); - Boy* boy = [objects objectAtIndex:0]; - Girl* girl = [objects objectAtIndex:1]; + Boy *boy = [objects objectAtIndex:0]; + Girl *girl = [objects objectAtIndex:1]; assertThat(boy.name, is(equalTo(@"Blake Watters"))); assertThat(girl.name, is(equalTo(@"Sarah"))); } -- (void)testShouldMapARelationshipDynamically { - RKObjectMapping* boyMapping = [RKObjectMapping mappingForClass:[Boy class]]; +- (void)testShouldMapARelationshipDynamically +{ + RKObjectMapping *boyMapping = [RKObjectMapping mappingForClass:[Boy class]]; [boyMapping mapAttributes:@"name", nil]; - RKObjectMapping* girlMapping = [RKObjectMapping mappingForClass:[Girl class]]; + RKObjectMapping *girlMapping = [RKObjectMapping mappingForClass:[Girl class]]; [girlMapping mapAttributes:@"name", nil]; - RKDynamicObjectMapping* dynamicMapping = [RKDynamicObjectMapping dynamicMapping]; + RKDynamicObjectMapping *dynamicMapping = [RKDynamicObjectMapping dynamicMapping]; [dynamicMapping setObjectMapping:boyMapping whenValueOfKeyPath:@"type" isEqualTo:@"Boy"]; [dynamicMapping setObjectMapping:girlMapping whenValueOfKeyPath:@"type" isEqualTo:@"Girl"]; [boyMapping mapKeyPath:@"friends" toRelationship:@"friends" withMapping:dynamicMapping]; - RKObjectMappingProvider* provider = [[RKObjectMappingProvider new] autorelease]; + RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; [provider setMapping:dynamicMapping forKeyPath:@""]; id mockProvider = [OCMockObject partialMockForObject:provider]; id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"friends.json"]; - RKObjectMapper* mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:mockProvider]; - Boy* blake = [[mapper performMapping] asObject]; - NSArray* friends = blake.friends; + RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:mockProvider]; + Boy *blake = [[mapper performMapping] asObject]; + NSArray *friends = blake.friends; assertThat(friends, hasCountOf(2)); assertThat([friends objectAtIndex:0], is(instanceOf([Boy class]))); assertThat([friends objectAtIndex:1], is(instanceOf([Girl class]))); - Boy* boy = [friends objectAtIndex:0]; - Girl* girl = [friends objectAtIndex:1]; + Boy *boy = [friends objectAtIndex:0]; + Girl *girl = [friends objectAtIndex:1]; assertThat(boy.name, is(equalTo(@"John Doe"))); assertThat(girl.name, is(equalTo(@"Jane Doe"))); } -- (void)testShouldBeAbleToDeclineMappingAnObjectByReturningANilObjectMapping { - RKObjectMapping* boyMapping = [RKObjectMapping mappingForClass:[Boy class]]; +- (void)testShouldBeAbleToDeclineMappingAnObjectByReturningANilObjectMapping +{ + RKObjectMapping *boyMapping = [RKObjectMapping mappingForClass:[Boy class]]; [boyMapping mapAttributes:@"name", nil]; - RKObjectMapping* girlMapping = [RKObjectMapping mappingForClass:[Girl class]]; + RKObjectMapping *girlMapping = [RKObjectMapping mappingForClass:[Girl class]]; [girlMapping mapAttributes:@"name", nil]; - RKDynamicObjectMapping* dynamicMapping = [RKDynamicObjectMapping dynamicMapping]; - dynamicMapping.objectMappingForDataBlock = ^ RKObjectMapping* (id mappableData) { + RKDynamicObjectMapping *dynamicMapping = [RKDynamicObjectMapping dynamicMapping]; + dynamicMapping.objectMappingForDataBlock = ^ RKObjectMapping *(id mappableData) { if ([[mappableData valueForKey:@"type"] isEqualToString:@"Boy"]) { return boyMapping; } else if ([[mappableData valueForKey:@"type"] isEqualToString:@"Girl"]) { @@ -1663,26 +1754,27 @@ - (void)testShouldBeAbleToDeclineMappingAnObjectByReturningANilObjectMapping { return nil; }; - RKObjectMappingProvider* provider = [[RKObjectMappingProvider new] autorelease]; + RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; [provider setMapping:dynamicMapping forKeyPath:@""]; id mockProvider = [OCMockObject partialMockForObject:provider]; id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"mixed.json"]; - RKObjectMapper* mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:mockProvider]; - NSArray* boys = [[mapper performMapping] asCollection]; + RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:mockProvider]; + NSArray *boys = [[mapper performMapping] asCollection]; assertThat(boys, hasCountOf(1)); - Boy* user = [boys objectAtIndex:0]; + Boy *user = [boys objectAtIndex:0]; assertThat(user, is(instanceOf([Boy class]))); assertThat(user.name, is(equalTo(@"Blake Watters"))); } -- (void)testShouldBeAbleToDeclineMappingObjectsInARelationshipByReturningANilObjectMapping { - RKObjectMapping* boyMapping = [RKObjectMapping mappingForClass:[Boy class]]; +- (void)testShouldBeAbleToDeclineMappingObjectsInARelationshipByReturningANilObjectMapping +{ + RKObjectMapping *boyMapping = [RKObjectMapping mappingForClass:[Boy class]]; [boyMapping mapAttributes:@"name", nil]; - RKObjectMapping* girlMapping = [RKObjectMapping mappingForClass:[Girl class]]; + RKObjectMapping *girlMapping = [RKObjectMapping mappingForClass:[Girl class]]; [girlMapping mapAttributes:@"name", nil]; - RKDynamicObjectMapping* dynamicMapping = [RKDynamicObjectMapping dynamicMapping]; - dynamicMapping.objectMappingForDataBlock = ^ RKObjectMapping* (id mappableData) { + RKDynamicObjectMapping *dynamicMapping = [RKDynamicObjectMapping dynamicMapping]; + dynamicMapping.objectMappingForDataBlock = ^ RKObjectMapping *(id mappableData) { if ([[mappableData valueForKey:@"type"] isEqualToString:@"Boy"]) { return boyMapping; } else if ([[mappableData valueForKey:@"type"] isEqualToString:@"Girl"]) { @@ -1694,29 +1786,30 @@ - (void)testShouldBeAbleToDeclineMappingObjectsInARelationshipByReturningANilObj }; [boyMapping mapKeyPath:@"friends" toRelationship:@"friends" withMapping:dynamicMapping]; - RKObjectMappingProvider* provider = [[RKObjectMappingProvider new] autorelease]; + RKObjectMappingProvider *provider = [[RKObjectMappingProvider new] autorelease]; [provider setMapping:dynamicMapping forKeyPath:@""]; id mockProvider = [OCMockObject partialMockForObject:provider]; id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"friends.json"]; - RKObjectMapper* mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:mockProvider]; - Boy* blake = [[mapper performMapping] asObject]; + RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:mockProvider]; + Boy *blake = [[mapper performMapping] asObject]; assertThat(blake, is(notNilValue())); assertThat(blake.name, is(equalTo(@"Blake Watters"))); assertThat(blake, is(instanceOf([Boy class]))); - NSArray* friends = blake.friends; + NSArray *friends = blake.friends; assertThat(friends, hasCountOf(1)); assertThat([friends objectAtIndex:0], is(instanceOf([Boy class]))); - Boy* boy = [friends objectAtIndex:0]; + Boy *boy = [friends objectAtIndex:0]; assertThat(boy.name, is(equalTo(@"John Doe"))); } -- (void)testShouldMapATargetObjectWithADynamicMapping { - RKObjectMapping* boyMapping = [RKObjectMapping mappingForClass:[Boy class]]; +- (void)testShouldMapATargetObjectWithADynamicMapping +{ + RKObjectMapping *boyMapping = [RKObjectMapping mappingForClass:[Boy class]]; [boyMapping mapAttributes:@"name", nil]; - RKDynamicObjectMapping* dynamicMapping = [RKDynamicObjectMapping dynamicMapping]; - dynamicMapping.objectMappingForDataBlock = ^ RKObjectMapping* (id mappableData) { + RKDynamicObjectMapping *dynamicMapping = [RKDynamicObjectMapping dynamicMapping]; + dynamicMapping.objectMappingForDataBlock = ^ RKObjectMapping *(id mappableData) { if ([[mappableData valueForKey:@"type"] isEqualToString:@"Boy"]) { return boyMapping; } @@ -1724,23 +1817,24 @@ - (void)testShouldMapATargetObjectWithADynamicMapping { return nil; }; - RKObjectMappingProvider* provider = [RKObjectMappingProvider objectMappingProvider]; + RKObjectMappingProvider *provider = [RKObjectMappingProvider objectMappingProvider]; [provider setMapping:dynamicMapping forKeyPath:@""]; id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"boy.json"]; - Boy* blake = [[Boy new] autorelease]; - RKObjectMapper* mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; + Boy *blake = [[Boy new] autorelease]; + RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; mapper.targetObject = blake; - Boy* user = [[mapper performMapping] asObject]; + Boy *user = [[mapper performMapping] asObject]; assertThat(user, is(instanceOf([Boy class]))); assertThat(user.name, is(equalTo(@"Blake Watters"))); } -- (void)testShouldBeBackwardsCompatibleWithTheOldClassName { - RKObjectMapping* boyMapping = [RKObjectMapping mappingForClass:[Boy class]]; +- (void)testShouldBeBackwardsCompatibleWithTheOldClassName +{ + RKObjectMapping *boyMapping = [RKObjectMapping mappingForClass:[Boy class]]; [boyMapping mapAttributes:@"name", nil]; - RKObjectDynamicMapping* dynamicMapping = (RKObjectDynamicMapping *) [RKObjectDynamicMapping dynamicMapping]; - dynamicMapping.objectMappingForDataBlock = ^ RKObjectMapping* (id mappableData) { + RKObjectDynamicMapping *dynamicMapping = (RKObjectDynamicMapping *)[RKObjectDynamicMapping dynamicMapping]; + dynamicMapping.objectMappingForDataBlock = ^ RKObjectMapping *(id mappableData) { if ([[mappableData valueForKey:@"type"] isEqualToString:@"Boy"]) { return boyMapping; } @@ -1748,43 +1842,45 @@ - (void)testShouldBeBackwardsCompatibleWithTheOldClassName { return nil; }; - RKObjectMappingProvider* provider = [RKObjectMappingProvider objectMappingProvider]; + RKObjectMappingProvider *provider = [RKObjectMappingProvider objectMappingProvider]; [provider setMapping:dynamicMapping forKeyPath:@""]; id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"boy.json"]; - Boy* blake = [[Boy new] autorelease]; - RKObjectMapper* mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; + Boy *blake = [[Boy new] autorelease]; + RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; mapper.targetObject = blake; - Boy* user = [[mapper performMapping] asObject]; + Boy *user = [[mapper performMapping] asObject]; assertThat(user, is(instanceOf([Boy class]))); assertThat(user.name, is(equalTo(@"Blake Watters"))); } -- (void)testShouldFailWithAnErrorIfATargetObjectIsProvidedAndTheDynamicMappingReturnsNil { - RKObjectMapping* boyMapping = [RKObjectMapping mappingForClass:[Boy class]]; +- (void)testShouldFailWithAnErrorIfATargetObjectIsProvidedAndTheDynamicMappingReturnsNil +{ + RKObjectMapping *boyMapping = [RKObjectMapping mappingForClass:[Boy class]]; [boyMapping mapAttributes:@"name", nil]; - RKDynamicObjectMapping* dynamicMapping = [RKDynamicObjectMapping dynamicMapping]; - dynamicMapping.objectMappingForDataBlock = ^ RKObjectMapping* (id mappableData) { + RKDynamicObjectMapping *dynamicMapping = [RKDynamicObjectMapping dynamicMapping]; + dynamicMapping.objectMappingForDataBlock = ^ RKObjectMapping *(id mappableData) { return nil; }; - RKObjectMappingProvider* provider = [RKObjectMappingProvider objectMappingProvider]; + RKObjectMappingProvider *provider = [RKObjectMappingProvider objectMappingProvider]; [provider setMapping:dynamicMapping forKeyPath:@""]; id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"boy.json"]; - Boy* blake = [[Boy new] autorelease]; - RKObjectMapper* mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; + Boy *blake = [[Boy new] autorelease]; + RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; mapper.targetObject = blake; - Boy* user = [[mapper performMapping] asObject]; + Boy *user = [[mapper performMapping] asObject]; assertThat(user, is(nilValue())); assertThat(mapper.errors, hasCountOf(1)); } -- (void)testShouldFailWithAnErrorIfATargetObjectIsProvidedAndTheDynamicMappingReturnsTheIncorrectType { - RKObjectMapping* girlMapping = [RKObjectMapping mappingForClass:[Girl class]]; +- (void)testShouldFailWithAnErrorIfATargetObjectIsProvidedAndTheDynamicMappingReturnsTheIncorrectType +{ + RKObjectMapping *girlMapping = [RKObjectMapping mappingForClass:[Girl class]]; [girlMapping mapAttributes:@"name", nil]; - RKDynamicObjectMapping* dynamicMapping = [RKDynamicObjectMapping dynamicMapping]; - dynamicMapping.objectMappingForDataBlock = ^ RKObjectMapping* (id mappableData) { + RKDynamicObjectMapping *dynamicMapping = [RKDynamicObjectMapping dynamicMapping]; + dynamicMapping.objectMappingForDataBlock = ^ RKObjectMapping *(id mappableData) { if ([[mappableData valueForKey:@"type"] isEqualToString:@"Girl"]) { return girlMapping; } @@ -1792,21 +1888,22 @@ - (void)testShouldFailWithAnErrorIfATargetObjectIsProvidedAndTheDynamicMappingRe return nil; }; - RKObjectMappingProvider* provider = [RKObjectMappingProvider objectMappingProvider]; + RKObjectMappingProvider *provider = [RKObjectMappingProvider objectMappingProvider]; [provider setMapping:dynamicMapping forKeyPath:@""]; id userInfo = [RKTestFixture parsedObjectWithContentsOfFixture:@"girl.json"]; - Boy* blake = [[Boy new] autorelease]; - RKObjectMapper* mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; + Boy *blake = [[Boy new] autorelease]; + RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:userInfo mappingProvider:provider]; mapper.targetObject = blake; - Boy* user = [[mapper performMapping] asObject]; + Boy *user = [[mapper performMapping] asObject]; assertThat(user, is(nilValue())); assertThat(mapper.errors, hasCountOf(1)); } #pragma mark - Date and Time Formatting -- (void)testShouldAutoConfigureDefaultDateFormatters { +- (void)testShouldAutoConfigureDefaultDateFormatters +{ [RKObjectMapping setDefaultDateFormatters:nil]; NSArray *dateFormatters = [RKObjectMapping defaultDateFormatters]; assertThat(dateFormatters, hasCountOf(3)); @@ -1817,14 +1914,16 @@ - (void)testShouldAutoConfigureDefaultDateFormatters { assertThat([[dateFormatters objectAtIndex:1] timeZone], is(equalTo(UTCTimeZone))); } -- (void)testShouldLetYouSetTheDefaultDateFormatters { +- (void)testShouldLetYouSetTheDefaultDateFormatters +{ NSDateFormatter *dateFormatter = [NSDateFormatter new]; NSArray *dateFormatters = [NSArray arrayWithObject:dateFormatter]; [RKObjectMapping setDefaultDateFormatters:dateFormatters]; assertThat([RKObjectMapping defaultDateFormatters], is(equalTo(dateFormatters))); } -- (void)testShouldLetYouAppendADateFormatterToTheList { +- (void)testShouldLetYouAppendADateFormatterToTheList +{ [RKObjectMapping setDefaultDateFormatters:nil]; assertThat([RKObjectMapping defaultDateFormatters], hasCountOf(3)); NSDateFormatter *dateFormatter = [NSDateFormatter new]; @@ -1832,7 +1931,8 @@ - (void)testShouldLetYouAppendADateFormatterToTheList { assertThat([RKObjectMapping defaultDateFormatters], hasCountOf(4)); } -- (void)testShouldAllowNewlyAddedDateFormatterToRunFirst { +- (void)testShouldAllowNewlyAddedDateFormatterToRunFirst +{ [RKObjectMapping setDefaultDateFormatters:nil]; NSDateFormatter *newDateFormatter = [[NSDateFormatter new] autorelease]; [newDateFormatter setDateFormat:@"dd/MM/yyyy"]; @@ -1859,7 +1959,8 @@ - (void)testShouldAllowNewlyAddedDateFormatterToRunFirst { assertThat([dateFormatter stringFromDate:user.favoriteDate], is(equalTo(@"01/03/2012"))); } -- (void)testShouldLetYouConfigureANewDateFormatterFromAStringAndATimeZone { +- (void)testShouldLetYouConfigureANewDateFormatterFromAStringAndATimeZone +{ [RKObjectMapping setDefaultDateFormatters:nil]; assertThat([RKObjectMapping defaultDateFormatters], hasCountOf(3)); NSTimeZone *EDTTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"EDT"]; @@ -1869,24 +1970,26 @@ - (void)testShouldLetYouConfigureANewDateFormatterFromAStringAndATimeZone { assertThat(dateFormatter.timeZone, is(equalTo(EDTTimeZone))); } -- (void)testShouldReturnNilForEmptyDateValues { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; - RKObjectAttributeMapping* birthDateMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"birthdate" toKeyPath:@"birthDate"]; +- (void)testShouldReturnNilForEmptyDateValues +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; + RKObjectAttributeMapping *birthDateMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"birthdate" toKeyPath:@"birthDate"]; [mapping addAttributeMapping:birthDateMapping]; - NSDictionary* dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; + NSDictionary *dictionary = [RKTestFixture parsedObjectWithContentsOfFixture:@"user.json"]; NSMutableDictionary *mutableDictionary = [dictionary mutableCopy]; [mutableDictionary setValue:@"" forKey:@"birthdate"]; - RKTestUser* user = [RKTestUser user]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:mutableDictionary destinationObject:user mapping:mapping]; + RKTestUser *user = [RKTestUser user]; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:mutableDictionary destinationObject:user mapping:mapping]; [mutableDictionary release]; - NSError* error = nil; + NSError *error = nil; [operation performMapping:&error]; assertThat(user.birthDate, is(equalTo(nil))); } -- (void)testShouldConfigureANewDateFormatterInTheUTCTimeZoneIfPassedANilTimeZone { +- (void)testShouldConfigureANewDateFormatterInTheUTCTimeZoneIfPassedANilTimeZone +{ [RKObjectMapping setDefaultDateFormatters:nil]; assertThat([RKObjectMapping defaultDateFormatters], hasCountOf(3)); [RKObjectMapping addDefaultDateFormatterForString:@"mm/dd/YYYY" inTimeZone:nil]; @@ -1899,10 +2002,11 @@ - (void)testShouldConfigureANewDateFormatterInTheUTCTimeZoneIfPassedANilTimeZone #pragma mark - Object Serialization // TODO: Move to RKObjectSerializerTest -- (void)testShouldSerializeHasOneRelatioshipsToJSON { - RKObjectMapping* userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; +- (void)testShouldSerializeHasOneRelatioshipsToJSON +{ + RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; [userMapping mapAttributes:@"name", nil]; - RKObjectMapping* addressMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; + RKObjectMapping *addressMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; [addressMapping mapAttributes:@"city", @"state", nil]; [userMapping hasOne:@"address" withMapping:addressMapping]; @@ -1913,17 +2017,18 @@ - (void)testShouldSerializeHasOneRelatioshipsToJSON { user.address = address; RKObjectMapping *serializationMapping = [userMapping inverseMapping]; - RKObjectSerializer* serializer = [RKObjectSerializer serializerWithObject:user mapping:serializationMapping]; - NSError* error = nil; + RKObjectSerializer *serializer = [RKObjectSerializer serializerWithObject:user mapping:serializationMapping]; + NSError *error = nil; NSString *JSON = [serializer serializedObjectForMIMEType:RKMIMETypeJSON error:&error]; assertThat(error, is(nilValue())); assertThat(JSON, is(equalTo(@"{\"name\":\"Blake Watters\",\"address\":{\"state\":\"North Carolina\"}}"))); } -- (void)testShouldSerializeHasManyRelationshipsToJSON { - RKObjectMapping* userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; +- (void)testShouldSerializeHasManyRelationshipsToJSON +{ + RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[RKTestUser class]]; [userMapping mapAttributes:@"name", nil]; - RKObjectMapping* addressMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; + RKObjectMapping *addressMapping = [RKObjectMapping mappingForClass:[RKTestAddress class]]; [addressMapping mapAttributes:@"city", @"state", nil]; [userMapping hasMany:@"friends" withMapping:addressMapping]; @@ -1937,18 +2042,19 @@ - (void)testShouldSerializeHasManyRelationshipsToJSON { RKObjectMapping *serializationMapping = [userMapping inverseMapping]; - RKObjectSerializer* serializer = [RKObjectSerializer serializerWithObject:user mapping:serializationMapping]; - NSError* error = nil; + RKObjectSerializer *serializer = [RKObjectSerializer serializerWithObject:user mapping:serializationMapping]; + NSError *error = nil; NSString *JSON = [serializer serializedObjectForMIMEType:RKMIMETypeJSON error:&error]; assertThat(error, is(nilValue())); assertThat(JSON, is(equalTo(@"{\"name\":\"Blake Watters\",\"friends\":[{\"city\":\"Carrboro\"},{\"city\":\"New York City\"}]}"))); } -- (void)testShouldSerializeManagedHasManyRelationshipsToJSON { +- (void)testShouldSerializeManagedHasManyRelationshipsToJSON +{ [RKTestFactory managedObjectStore]; - RKObjectMapping* humanMapping = [RKObjectMapping mappingForClass:[RKHuman class]]; + RKObjectMapping *humanMapping = [RKObjectMapping mappingForClass:[RKHuman class]]; [humanMapping mapAttributes:@"name", nil]; - RKObjectMapping* catMapping = [RKObjectMapping mappingForClass:[RKCat class]]; + RKObjectMapping *catMapping = [RKObjectMapping mappingForClass:[RKCat class]]; [catMapping mapAttributes:@"name", nil]; [humanMapping hasMany:@"cats" withMapping:catMapping]; @@ -1961,8 +2067,8 @@ - (void)testShouldSerializeManagedHasManyRelationshipsToJSON { blake.cats = [NSSet setWithObjects:asia, roy, nil]; RKObjectMapping *serializationMapping = [humanMapping inverseMapping]; - RKObjectSerializer* serializer = [RKObjectSerializer serializerWithObject:blake mapping:serializationMapping]; - NSError* error = nil; + RKObjectSerializer *serializer = [RKObjectSerializer serializerWithObject:blake mapping:serializationMapping]; + NSError *error = nil; NSString *JSON = [serializer serializedObjectForMIMEType:RKMIMETypeJSON error:&error]; NSDictionary *parsedJSON = [JSON performSelector:@selector(objectFromJSONString)]; assertThat(error, is(nilValue())); @@ -1971,7 +2077,8 @@ - (void)testShouldSerializeManagedHasManyRelationshipsToJSON { assertThat(catNames, is(equalTo([NSArray arrayWithObjects:@"Asia", @"Roy", nil]))); } -- (void)testUpdatingArrayOfExistingCats { +- (void)testUpdatingArrayOfExistingCats +{ RKManagedObjectStore *objectStore = [RKTestFactory managedObjectStore]; NSArray *array = [RKTestFixture parsedObjectWithContentsOfFixture:@"ArrayOfHumans.json"]; RKManagedObjectMapping *humanMapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:objectStore]; diff --git a/Tests/Logic/ObjectMapping/RKObjectMappingOperationTest.m b/Tests/Logic/ObjectMapping/RKObjectMappingOperationTest.m index 1a7c5209ff..2213af3004 100644 --- a/Tests/Logic/ObjectMapping/RKObjectMappingOperationTest.m +++ b/Tests/Logic/ObjectMapping/RKObjectMappingOperationTest.m @@ -49,7 +49,8 @@ @implementation TestMappable @synthesize orderedSet = _orderedSet; @synthesize array = _array; -- (BOOL)validateBoolString:(id *)ioValue error:(NSError **)outError { +- (BOOL)validateBoolString:(id *)ioValue error:(NSError **)outError +{ if ([(NSObject *)*ioValue isKindOfClass:[NSString class]] && [(NSString *)*ioValue isEqualToString:@"FAIL"]) { *outError = [NSError errorWithDomain:RKErrorDomain code:RKObjectMapperErrorUnmappableContent userInfo:nil]; return NO; @@ -73,92 +74,98 @@ @interface RKObjectMappingOperationTest : RKTestCase { @implementation RKObjectMappingOperationTest -- (void)testShouldNotUpdateEqualURLProperties { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[TestMappable class]]; +- (void)testShouldNotUpdateEqualURLProperties +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[TestMappable class]]; [mapping mapAttributes:@"url", nil]; - NSURL* url1 = [NSURL URLWithString:@"http://www.restkit.org"]; - NSURL* url2 = [NSURL URLWithString:@"http://www.restkit.org"]; + NSURL *url1 = [NSURL URLWithString:@"http://www.restkit.org"]; + NSURL *url2 = [NSURL URLWithString:@"http://www.restkit.org"]; assertThatBool(url1 == url2, is(equalToBool(NO))); - TestMappable* object = [[[TestMappable alloc] init] autorelease]; + TestMappable *object = [[[TestMappable alloc] init] autorelease]; [object setUrl:url1]; - NSDictionary* dictionary = [NSDictionary dictionaryWithObjectsAndKeys:url2, @"url", nil]; + NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:url2, @"url", nil]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:object mapping:mapping]; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:object mapping:mapping]; BOOL success = [operation performMapping:nil]; assertThatBool(success, is(equalToBool(YES))); assertThatBool(object.url == url1, is(equalToBool(YES))); [operation release]; } -- (void)testShouldSuccessfullyMapBoolsToStrings { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[TestMappable class]]; +- (void)testShouldSuccessfullyMapBoolsToStrings +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[TestMappable class]]; [mapping mapAttributes:@"boolString", nil]; - TestMappable* object = [[[TestMappable alloc] init] autorelease]; + TestMappable *object = [[[TestMappable alloc] init] autorelease]; id parser = [[RKParserRegistry sharedRegistry] parserForMIMEType:@"application/json"]; id data = [parser objectFromString:@"{\"boolString\":true}" error:nil]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:data destinationObject:object mapping:mapping]; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:data destinationObject:object mapping:mapping]; BOOL success = [operation performMapping:nil]; assertThatBool(success, is(equalToBool(YES))); assertThat(object.boolString, is(equalTo(@"true"))); [operation release]; } -- (void)testShouldSuccessfullyMapTrueBoolsToNSNumbers { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[TestMappable class]]; +- (void)testShouldSuccessfullyMapTrueBoolsToNSNumbers +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[TestMappable class]]; [mapping mapAttributes:@"boolNumber", nil]; - TestMappable* object = [[[TestMappable alloc] init] autorelease]; + TestMappable *object = [[[TestMappable alloc] init] autorelease]; id parser = [[RKParserRegistry sharedRegistry] parserForMIMEType:@"application/json"]; id data = [parser objectFromString:@"{\"boolNumber\":true}" error:nil]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:data destinationObject:object mapping:mapping]; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:data destinationObject:object mapping:mapping]; BOOL success = [operation performMapping:nil]; assertThatBool(success, is(equalToBool(YES))); assertThatInt([object.boolNumber intValue], is(equalToInt(1))); [operation release]; } -- (void)testShouldSuccessfullyMapFalseBoolsToNSNumbers { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[TestMappable class]]; +- (void)testShouldSuccessfullyMapFalseBoolsToNSNumbers +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[TestMappable class]]; [mapping mapAttributes:@"boolNumber", nil]; - TestMappable* object = [[[TestMappable alloc] init] autorelease]; + TestMappable *object = [[[TestMappable alloc] init] autorelease]; id parser = [[RKParserRegistry sharedRegistry] parserForMIMEType:@"application/json"]; id data = [parser objectFromString:@"{\"boolNumber\":false}" error:nil]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:data destinationObject:object mapping:mapping]; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:data destinationObject:object mapping:mapping]; BOOL success = [operation performMapping:nil]; assertThatBool(success, is(equalToBool(YES))); assertThatInt([object.boolNumber intValue], is(equalToInt(0))); [operation release]; } -- (void)testShouldSuccessfullyMapNumbersToStrings { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[TestMappable class]]; +- (void)testShouldSuccessfullyMapNumbersToStrings +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[TestMappable class]]; [mapping mapKeyPath:@"number" toAttribute:@"boolString"]; - TestMappable* object = [[[TestMappable alloc] init] autorelease]; + TestMappable *object = [[[TestMappable alloc] init] autorelease]; id parser = [[RKParserRegistry sharedRegistry] parserForMIMEType:@"application/json"]; id data = [parser objectFromString:@"{\"number\":123}" error:nil]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:data destinationObject:object mapping:mapping]; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:data destinationObject:object mapping:mapping]; BOOL success = [operation performMapping:nil]; assertThatBool(success, is(equalToBool(YES))); assertThat(object.boolString, is(equalTo(@"123"))); [operation release]; } -- (void)testShouldSuccessfullyMapArraysToOrderedSets { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[TestMappable class]]; +- (void)testShouldSuccessfullyMapArraysToOrderedSets +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[TestMappable class]]; [mapping mapKeyPath:@"numbers" toAttribute:@"orderedSet"]; - TestMappable* object = [[[TestMappable alloc] init] autorelease]; + TestMappable *object = [[[TestMappable alloc] init] autorelease]; id parser = [[RKParserRegistry sharedRegistry] parserForMIMEType:@"application/json"]; id data = [parser objectFromString:@"{\"numbers\":[1, 2, 3]}" error:nil]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:data destinationObject:object mapping:mapping]; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:data destinationObject:object mapping:mapping]; BOOL success = [operation performMapping:nil]; assertThatBool(success, is(equalToBool(YES))); NSOrderedSet *expectedSet = [NSOrderedSet orderedSetWithObjects:[NSNumber numberWithInt:1], [NSNumber numberWithInt:2], [NSNumber numberWithInt:3], nil]; @@ -166,56 +173,60 @@ - (void)testShouldSuccessfullyMapArraysToOrderedSets { [operation release]; } -- (void)testShouldSuccessfullyMapOrderedSetsToArrays { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[TestMappable class]]; +- (void)testShouldSuccessfullyMapOrderedSetsToArrays +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[TestMappable class]]; [mapping mapKeyPath:@"orderedSet" toAttribute:@"array"]; - TestMappable* object = [[[TestMappable alloc] init] autorelease]; + TestMappable *object = [[[TestMappable alloc] init] autorelease]; - TestMappable* data = [[[TestMappable alloc] init] autorelease]; + TestMappable *data = [[[TestMappable alloc] init] autorelease]; data.orderedSet = [NSOrderedSet orderedSetWithObjects:[NSNumber numberWithInt:1], [NSNumber numberWithInt:2], [NSNumber numberWithInt:3], nil]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:data destinationObject:object mapping:mapping]; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:data destinationObject:object mapping:mapping]; BOOL success = [operation performMapping:nil]; assertThatBool(success, is(equalToBool(YES))); - NSArray* expectedArray = [NSArray arrayWithObjects:[NSNumber numberWithInt:1], [NSNumber numberWithInt:2], [NSNumber numberWithInt:3], nil]; + NSArray *expectedArray = [NSArray arrayWithObjects:[NSNumber numberWithInt:1], [NSNumber numberWithInt:2], [NSNumber numberWithInt:3], nil]; assertThat(object.array, is(equalTo(expectedArray))); [operation release]; } -- (void)testShouldFailTheMappingOperationIfKeyValueValidationSetsAnError { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[TestMappable class]]; +- (void)testShouldFailTheMappingOperationIfKeyValueValidationSetsAnError +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[TestMappable class]]; [mapping mapAttributes:@"boolString", nil]; - TestMappable* object = [[[TestMappable alloc] init] autorelease]; - NSDictionary* dictionary = [NSDictionary dictionaryWithObject:@"FAIL" forKey:@"boolString"]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:object mapping:mapping]; - NSError* error = nil; + TestMappable *object = [[[TestMappable alloc] init] autorelease]; + NSDictionary *dictionary = [NSDictionary dictionaryWithObject:@"FAIL" forKey:@"boolString"]; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:object mapping:mapping]; + NSError *error = nil; BOOL success = [operation performMapping:&error]; assertThatBool(success, is(equalToBool(NO))); assertThat(error, isNot(nilValue())); [operation release]; } -- (void)testShouldNotSetTheAttributeIfKeyValueValidationReturnsNo { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[TestMappable class]]; +- (void)testShouldNotSetTheAttributeIfKeyValueValidationReturnsNo +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[TestMappable class]]; [mapping mapAttributes:@"boolString", nil]; - TestMappable* object = [[[TestMappable alloc] init] autorelease]; + TestMappable *object = [[[TestMappable alloc] init] autorelease]; object.boolString = @"should not change"; - NSDictionary* dictionary = [NSDictionary dictionaryWithObject:@"REJECT" forKey:@"boolString"]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:object mapping:mapping]; - NSError* error = nil; + NSDictionary *dictionary = [NSDictionary dictionaryWithObject:@"REJECT" forKey:@"boolString"]; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:object mapping:mapping]; + NSError *error = nil; BOOL success = [operation performMapping:&error]; assertThatBool(success, is(equalToBool(YES))); assertThat(object.boolString, is(equalTo(@"should not change"))); [operation release]; } -- (void)testModifyingValueWithinKeyValueValidationIsRespected { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[TestMappable class]]; +- (void)testModifyingValueWithinKeyValueValidationIsRespected +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[TestMappable class]]; [mapping mapAttributes:@"boolString", nil]; - TestMappable* object = [[[TestMappable alloc] init] autorelease]; - NSDictionary* dictionary = [NSDictionary dictionaryWithObject:@"MODIFY" forKey:@"boolString"]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:object mapping:mapping]; - NSError* error = nil; + TestMappable *object = [[[TestMappable alloc] init] autorelease]; + NSDictionary *dictionary = [NSDictionary dictionaryWithObject:@"MODIFY" forKey:@"boolString"]; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:object mapping:mapping]; + NSError *error = nil; BOOL success = [operation performMapping:&error]; assertThatBool(success, is(equalToBool(YES))); assertThat(object.boolString, is(equalTo(@"modified value"))); @@ -224,13 +235,14 @@ - (void)testModifyingValueWithinKeyValueValidationIsRespected { #pragma mark - TimeZone Handling -- (void)testShouldMapAUTCDateWithoutChangingTheTimeZone { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[TestMappable class]]; +- (void)testShouldMapAUTCDateWithoutChangingTheTimeZone +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[TestMappable class]]; [mapping mapAttributes:@"date", nil]; - TestMappable* object = [[[TestMappable alloc] init] autorelease]; - NSDictionary* dictionary = [NSDictionary dictionaryWithObject:@"2011-07-07T04:35:28Z" forKey:@"date"]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:object mapping:mapping]; - NSError* error = nil; + TestMappable *object = [[[TestMappable alloc] init] autorelease]; + NSDictionary *dictionary = [NSDictionary dictionaryWithObject:@"2011-07-07T04:35:28Z" forKey:@"date"]; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:object mapping:mapping]; + NSError *error = nil; BOOL success = [operation performMapping:&error]; assertThatBool(success, is(equalToBool(YES))); assertThat(object.date, isNot(nilValue())); @@ -238,13 +250,14 @@ - (void)testShouldMapAUTCDateWithoutChangingTheTimeZone { [operation release]; } -- (void)testShouldMapAUnixTimestampStringAppropriately { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[TestMappable class]]; +- (void)testShouldMapAUnixTimestampStringAppropriately +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[TestMappable class]]; [mapping mapAttributes:@"date", nil]; - TestMappable* object = [[[TestMappable alloc] init] autorelease]; - NSDictionary* dictionary = [NSDictionary dictionaryWithObject:@"457574400" forKey:@"date"]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:object mapping:mapping]; - NSError* error = nil; + TestMappable *object = [[[TestMappable alloc] init] autorelease]; + NSDictionary *dictionary = [NSDictionary dictionaryWithObject:@"457574400" forKey:@"date"]; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:object mapping:mapping]; + NSError *error = nil; BOOL success = [operation performMapping:&error]; assertThatBool(success, is(equalToBool(YES))); assertThat(object.date, isNot(nilValue())); @@ -252,13 +265,14 @@ - (void)testShouldMapAUnixTimestampStringAppropriately { [operation release]; } -- (void)testShouldMapASimpleDateStringAppropriately { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[TestMappable class]]; +- (void)testShouldMapASimpleDateStringAppropriately +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[TestMappable class]]; [mapping mapAttributes:@"date", nil]; - TestMappable* object = [[[TestMappable alloc] init] autorelease]; - NSDictionary* dictionary = [NSDictionary dictionaryWithObject:@"08/09/2011" forKey:@"date"]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:object mapping:mapping]; - NSError* error = nil; + TestMappable *object = [[[TestMappable alloc] init] autorelease]; + NSDictionary *dictionary = [NSDictionary dictionaryWithObject:@"08/09/2011" forKey:@"date"]; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:object mapping:mapping]; + NSError *error = nil; BOOL success = [operation performMapping:&error]; assertThatBool(success, is(equalToBool(YES))); assertThat(object.date, isNot(nilValue())); @@ -266,13 +280,14 @@ - (void)testShouldMapASimpleDateStringAppropriately { [operation release]; } -- (void)testShouldMapAISODateStringAppropriately { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[TestMappable class]]; +- (void)testShouldMapAISODateStringAppropriately +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[TestMappable class]]; [mapping mapAttributes:@"date", nil]; - TestMappable* object = [[[TestMappable alloc] init] autorelease]; - NSDictionary* dictionary = [NSDictionary dictionaryWithObject:@"2011-08-09T00:00Z" forKey:@"date"]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:object mapping:mapping]; - NSError* error = nil; + TestMappable *object = [[[TestMappable alloc] init] autorelease]; + NSDictionary *dictionary = [NSDictionary dictionaryWithObject:@"2011-08-09T00:00Z" forKey:@"date"]; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:object mapping:mapping]; + NSError *error = nil; BOOL success = [operation performMapping:&error]; assertThatBool(success, is(equalToBool(YES))); assertThat(object.date, isNot(nilValue())); @@ -280,18 +295,19 @@ - (void)testShouldMapAISODateStringAppropriately { [operation release]; } -- (void)testShouldMapAStringIntoTheLocalTimeZone { +- (void)testShouldMapAStringIntoTheLocalTimeZone +{ NSTimeZone *EDTTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"EDT"]; NSDateFormatter *dateFormatter = [[NSDateFormatter new] autorelease]; dateFormatter.dateFormat = @"MM-dd-yyyy"; dateFormatter.timeZone = EDTTimeZone; - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[TestMappable class]]; + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[TestMappable class]]; [mapping mapAttributes:@"date", nil]; mapping.dateFormatters = [NSArray arrayWithObject:dateFormatter]; - TestMappable* object = [[[TestMappable alloc] init] autorelease]; - NSDictionary* dictionary = [NSDictionary dictionaryWithObject:@"11-27-1982" forKey:@"date"]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:object mapping:mapping]; - NSError* error = nil; + TestMappable *object = [[[TestMappable alloc] init] autorelease]; + NSDictionary *dictionary = [NSDictionary dictionaryWithObject:@"11-27-1982" forKey:@"date"]; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:dictionary destinationObject:object mapping:mapping]; + NSError *error = nil; BOOL success = [operation performMapping:&error]; assertThatBool(success, is(equalToBool(YES))); assertThat(object.date, isNot(nilValue())); @@ -300,34 +316,36 @@ - (void)testShouldMapAStringIntoTheLocalTimeZone { [operation release]; } -- (void)testShouldMapADateToAStringUsingThePreferredDateFormatter { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[TestMappable class]]; +- (void)testShouldMapADateToAStringUsingThePreferredDateFormatter +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[TestMappable class]]; [mapping mapKeyPath:@"date" toAttribute:@"boolString"]; NSDateFormatter *dateFormatter = [[NSDateFormatter new] autorelease]; dateFormatter.dateFormat = @"MM-dd-yyyy"; dateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0]; - TestMappable* object = [[[TestMappable alloc] init] autorelease]; + TestMappable *object = [[[TestMappable alloc] init] autorelease]; object.date = [dateFormatter dateFromString:@"11-27-1982"]; mapping.preferredDateFormatter = dateFormatter; TestMappable *newObject = [TestMappable new]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:object destinationObject:newObject mapping:mapping]; - NSError* error = nil; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:object destinationObject:newObject mapping:mapping]; + NSError *error = nil; BOOL success = [operation performMapping:&error]; assertThatBool(success, is(equalToBool(YES))); assertThat(newObject.boolString, is(equalTo(@"11-27-1982"))); } -- (void)testShouldGenerateAnUnknownKeyPathExceptionWhenIgnoreUnknownKeyPathsIsNO { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; +- (void)testShouldGenerateAnUnknownKeyPathExceptionWhenIgnoreUnknownKeyPathsIsNO +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; [mapping mapAttributes:@"invalid", @"boolString", nil]; mapping.ignoreUnknownKeyPaths = NO; - TestMappable* object = [[[TestMappable alloc] init] autorelease]; + TestMappable *object = [[[TestMappable alloc] init] autorelease]; object.boolString = @"test"; - NSMutableDictionary* dictionary = [NSMutableDictionary dictionary]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:object destinationObject:dictionary mapping:mapping]; - NSError* error = nil; + NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:object destinationObject:dictionary mapping:mapping]; + NSError *error = nil; BOOL success; - NSException* exception = nil; + NSException *exception = nil; @try { success = [operation performMapping:&error]; } @@ -340,17 +358,18 @@ - (void)testShouldGenerateAnUnknownKeyPathExceptionWhenIgnoreUnknownKeyPathsIsNO } } -- (void)testShouldOptionallyIgnoreUnknownKeyPathAttributes { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; +- (void)testShouldOptionallyIgnoreUnknownKeyPathAttributes +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; [mapping mapAttributes:@"invalid", @"boolString", nil]; mapping.ignoreUnknownKeyPaths = YES; - TestMappable* object = [[[TestMappable alloc] init] autorelease]; + TestMappable *object = [[[TestMappable alloc] init] autorelease]; object.boolString = @"test"; - NSMutableDictionary* dictionary = [NSMutableDictionary dictionary]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:object destinationObject:dictionary mapping:mapping]; - NSError* error = nil; + NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:object destinationObject:dictionary mapping:mapping]; + NSError *error = nil; BOOL success; - NSException* exception = nil; + NSException *exception = nil; @try { success = [operation performMapping:&error]; } @@ -364,18 +383,19 @@ - (void)testShouldOptionallyIgnoreUnknownKeyPathAttributes { } } -- (void)testShouldOptionallyIgnoreUnknownKeyPathRelationships { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; +- (void)testShouldOptionallyIgnoreUnknownKeyPathRelationships +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; [mapping mapAttributes:@"boolString", nil]; [mapping mapRelationship:@"invalid" withMapping:[RKObjectMapping mappingForClass:[TestMappable class]]]; mapping.ignoreUnknownKeyPaths = YES; - TestMappable* object = [[[TestMappable alloc] init] autorelease]; + TestMappable *object = [[[TestMappable alloc] init] autorelease]; object.boolString = @"test"; - NSMutableDictionary* dictionary = [NSMutableDictionary dictionary]; - RKObjectMappingOperation* operation = [[RKObjectMappingOperation alloc] initWithSourceObject:object destinationObject:dictionary mapping:mapping]; - NSError* error = nil; + NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; + RKObjectMappingOperation *operation = [[RKObjectMappingOperation alloc] initWithSourceObject:object destinationObject:dictionary mapping:mapping]; + NSError *error = nil; BOOL success; - NSException* exception = nil; + NSException *exception = nil; @try { success = [operation performMapping:&error]; } @@ -389,7 +409,8 @@ - (void)testShouldOptionallyIgnoreUnknownKeyPathRelationships { } } -- (void)testShouldLogADebugMessageIfTheRelationshipMappingTargetsAnArrayOfArrays { +- (void)testShouldLogADebugMessageIfTheRelationshipMappingTargetsAnArrayOfArrays +{ // Create a dictionary with a dictionary containing an array // Use keyPath to traverse to the collection and target a hasMany id data = [RKTestFixture parsedObjectWithContentsOfFixture:@"ArrayOfNestedDictionaries.json"]; diff --git a/Tests/Logic/ObjectMapping/RKObjectMappingProviderTest.m b/Tests/Logic/ObjectMapping/RKObjectMappingProviderTest.m index 2f7f0fba08..126e47caab 100644 --- a/Tests/Logic/ObjectMapping/RKObjectMappingProviderTest.m +++ b/Tests/Logic/ObjectMapping/RKObjectMappingProviderTest.m @@ -31,23 +31,25 @@ #import "RKOrderedDictionary.h" @interface RKObjectMappingProviderTest : RKTestCase { - RKObjectManager* _objectManager; + RKObjectManager *_objectManager; } @end @implementation RKObjectMappingProviderTest -- (void)setUp { +- (void)setUp +{ _objectManager = [RKTestFactory objectManager]; _objectManager.objectStore = [RKManagedObjectStore objectStoreWithStoreFilename:@"RKTests.sqlite"]; [RKObjectManager setSharedManager:_objectManager]; [_objectManager.objectStore deletePersistentStore]; } -- (void)testShouldFindAnExistingObjectMappingForAClass { +- (void)testShouldFindAnExistingObjectMappingForAClass +{ RKManagedObjectStore *objectStore = [RKTestFactory managedObjectStore]; - RKManagedObjectMapping* humanMapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:objectStore]; + RKManagedObjectMapping *humanMapping = [RKManagedObjectMapping mappingForClass:[RKHuman class] inManagedObjectStore:objectStore]; assertThat(humanMapping, isNot(equalTo(nil))); [humanMapping mapAttributes:@"name", nil]; [_objectManager.mappingProvider addObjectMapping:humanMapping]; @@ -56,9 +58,10 @@ - (void)testShouldFindAnExistingObjectMappingForAClass { assertThat(returnedMapping, is(equalTo(humanMapping))); } -- (void)testShouldFindAnExistingObjectMappingForAKeyPath { +- (void)testShouldFindAnExistingObjectMappingForAKeyPath +{ RKManagedObjectStore *objectStore = [RKTestFactory managedObjectStore]; - RKManagedObjectMapping* catMapping = [RKManagedObjectMapping mappingForClass:[RKCat class] inManagedObjectStore:objectStore]; + RKManagedObjectMapping *catMapping = [RKManagedObjectMapping mappingForClass:[RKCat class] inManagedObjectStore:objectStore]; assertThat(catMapping, isNot(equalTo(nil))); [catMapping mapAttributes:@"name", nil]; [_objectManager.mappingProvider setMapping:catMapping forKeyPath:@"cat"]; @@ -67,10 +70,11 @@ - (void)testShouldFindAnExistingObjectMappingForAKeyPath { assertThat(returnedMapping, is(equalTo(catMapping))); } -- (void)testShouldAllowYouToRemoveAMappingByKeyPath { +- (void)testShouldAllowYouToRemoveAMappingByKeyPath +{ RKManagedObjectStore *objectStore = [RKTestFactory managedObjectStore]; RKObjectMappingProvider *mappingProvider = [RKObjectMappingProvider mappingProvider]; - RKManagedObjectMapping* catMapping = [RKManagedObjectMapping mappingForClass:[RKCat class] inManagedObjectStore:objectStore]; + RKManagedObjectMapping *catMapping = [RKManagedObjectMapping mappingForClass:[RKCat class] inManagedObjectStore:objectStore]; assertThat(catMapping, isNot(equalTo(nil))); [catMapping mapAttributes:@"name", nil]; [mappingProvider setMapping:catMapping forKeyPath:@"cat"]; @@ -81,39 +85,45 @@ - (void)testShouldAllowYouToRemoveAMappingByKeyPath { assertThat(returnedMapping, is(nilValue())); } -- (void)testSettingMappingInAContext { +- (void)testSettingMappingInAContext +{ RKObjectMappingProvider *mappingProvider = [RKObjectMappingProvider mappingProvider]; RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSMutableArray class]]; STAssertNoThrow([mappingProvider setMapping:mapping context:1], nil); } -- (void)testRetrievalOfMapping { +- (void)testRetrievalOfMapping +{ RKObjectMappingProvider *mappingProvider = [RKObjectMappingProvider mappingProvider]; RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSMutableArray class]]; [mappingProvider setMapping:mapping context:1]; assertThat([mappingProvider mappingForContext:1], is(equalTo(mapping))); } -- (void)testRetrievalOfMappingsCollectionForUndefinedContextReturnsEmptyArray { +- (void)testRetrievalOfMappingsCollectionForUndefinedContextReturnsEmptyArray +{ RKObjectMappingProvider *mappingProvider = [RKObjectMappingProvider mappingProvider]; NSArray *collection = [mappingProvider mappingsForContext:1]; assertThat(collection, is(empty())); } -- (void)testRetrievalOfMappingsCollectionWhenSingleMappingIsStoredRaisesError { +- (void)testRetrievalOfMappingsCollectionWhenSingleMappingIsStoredRaisesError +{ RKObjectMappingProvider *mappingProvider = [RKObjectMappingProvider mappingProvider]; RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSMutableArray class]]; [mappingProvider setMapping:mapping context:1]; STAssertThrows([mappingProvider mappingsForContext:1], @"Expected collection mapping retrieval to throw due to storage of single mapping"); } -- (void)testAddingMappingToCollectionContext { +- (void)testAddingMappingToCollectionContext +{ RKObjectMappingProvider *mappingProvider = [RKObjectMappingProvider mappingProvider]; RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSMutableArray class]]; STAssertNoThrow([mappingProvider addMapping:mapping context:1], nil); } -- (void)testRetrievalOfMappingCollection { +- (void)testRetrievalOfMappingCollection +{ RKObjectMappingProvider *mappingProvider = [RKObjectMappingProvider mappingProvider]; RKObjectMapping *mapping_1 = [RKObjectMapping mappingForClass:[NSMutableArray class]]; [mappingProvider addMapping:mapping_1 context:1]; @@ -123,7 +133,8 @@ - (void)testRetrievalOfMappingCollection { assertThat(collection, hasItems(mapping_1, mapping_2, nil)); } -- (void)testRetrievalOfMappingCollectionReturnsImmutableArray { +- (void)testRetrievalOfMappingCollectionReturnsImmutableArray +{ RKObjectMappingProvider *mappingProvider = [RKObjectMappingProvider mappingProvider]; RKObjectMapping *mapping_1 = [RKObjectMapping mappingForClass:[NSMutableArray class]]; [mappingProvider addMapping:mapping_1 context:1]; @@ -133,7 +144,8 @@ - (void)testRetrievalOfMappingCollectionReturnsImmutableArray { assertThat(collection, isNot(instanceOf([NSMutableArray class]))); } -- (void)testRemovalOfMappingFromCollection { +- (void)testRemovalOfMappingFromCollection +{ RKObjectMappingProvider *mappingProvider = [RKObjectMappingProvider mappingProvider]; RKObjectMapping *mapping_1 = [RKObjectMapping mappingForClass:[NSMutableArray class]]; [mappingProvider addMapping:mapping_1 context:1]; @@ -144,26 +156,30 @@ - (void)testRemovalOfMappingFromCollection { assertThat(collection, onlyContains(mapping_2, nil)); } -- (void)testAttemptToRemoveMappingFromContextThatDoesNotIncludeItRaisesError { +- (void)testAttemptToRemoveMappingFromContextThatDoesNotIncludeItRaisesError +{ RKObjectMappingProvider *mappingProvider = [RKObjectMappingProvider mappingProvider]; RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSMutableArray class]]; STAssertThrows([mappingProvider removeMapping:mapping context:1], @"Removal of mapping not included in context should raise an error."); } -- (void)testSettingMappingForKeyPathInContext { +- (void)testSettingMappingForKeyPathInContext +{ RKObjectMappingProvider *mappingProvider = [RKObjectMappingProvider mappingProvider]; RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSMutableArray class]]; STAssertNoThrow([mappingProvider setMapping:mapping forKeyPath:@"testing" context:1], nil); } -- (void)testRetrievalOfMappingForKeyPathInContext { +- (void)testRetrievalOfMappingForKeyPathInContext +{ RKObjectMappingProvider *mappingProvider = [RKObjectMappingProvider mappingProvider]; RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSMutableArray class]]; [mappingProvider setMapping:mapping forKeyPath:@"testing" context:1]; assertThat([mappingProvider mappingForKeyPath:@"testing" context:1], is(equalTo(mapping))); } -- (void)testRemovalOfMappingByKeyPathInContext { +- (void)testRemovalOfMappingByKeyPathInContext +{ RKObjectMappingProvider *mappingProvider = [RKObjectMappingProvider mappingProvider]; RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSMutableArray class]]; [mappingProvider setMapping:mapping forKeyPath:@"testing" context:1]; @@ -171,7 +187,8 @@ - (void)testRemovalOfMappingByKeyPathInContext { assertThat([mappingProvider mappingForKeyPath:@"testing" context:1], is(nilValue())); } -- (void)testSettingMappingForPathMatcherCreatesOrderedDictionary { +- (void)testSettingMappingForPathMatcherCreatesOrderedDictionary +{ RKObjectMappingProvider *mappingProvider = [RKObjectMappingProvider mappingProvider]; RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSMutableArray class]]; [mappingProvider setMapping:mapping forPattern:@"/articles/:id" context:1]; @@ -179,7 +196,8 @@ - (void)testSettingMappingForPathMatcherCreatesOrderedDictionary { assertThat(contextValue, is(instanceOf([RKOrderedDictionary class]))); } -- (void)testSettingMappingForPathMatcherCreatesDictionaryWithPathMatcherAsKey { +- (void)testSettingMappingForPathMatcherCreatesDictionaryWithPathMatcherAsKey +{ RKObjectMappingProvider *mappingProvider = [RKObjectMappingProvider mappingProvider]; RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSMutableArray class]]; [mappingProvider setMapping:mapping forPattern:@"/articles/:id" context:1]; @@ -187,7 +205,8 @@ - (void)testSettingMappingForPathMatcherCreatesDictionaryWithPathMatcherAsKey { assertThat([contextValue allKeys], contains(@"/articles/:id", nil)); } -- (void)testSettingMappingForPathMatcherCreatesDictionaryWithMappingAsValue { +- (void)testSettingMappingForPathMatcherCreatesDictionaryWithMappingAsValue +{ RKObjectMappingProvider *mappingProvider = [RKObjectMappingProvider mappingProvider]; RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSMutableArray class]]; RKObjectMappingProviderContextEntry *entry = [RKObjectMappingProviderContextEntry contextEntryWithMapping:mapping]; @@ -196,25 +215,28 @@ - (void)testSettingMappingForPathMatcherCreatesDictionaryWithMappingAsValue { assertThat([contextValue allValues], contains(entry, nil)); } -- (void)testRetrievalOfMappingForPathMatcher { +- (void)testRetrievalOfMappingForPathMatcher +{ RKObjectMappingProvider *mappingProvider = [RKObjectMappingProvider mappingProvider]; RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSMutableArray class]]; [mappingProvider setMapping:mapping forPattern:@"/articles/:id" context:1]; - RKObjectMappingDefinition * matchedMapping = [mappingProvider mappingForPatternMatchingString:@"/articles/12345" context:1]; + RKObjectMappingDefinition *matchedMapping = [mappingProvider mappingForPatternMatchingString:@"/articles/12345" context:1]; assertThat(matchedMapping, is(equalTo(mapping))); } -- (void)testRetrievalOfMappingForPathMatcherIncludingQueryParameters { +- (void)testRetrievalOfMappingForPathMatcherIncludingQueryParameters +{ RKObjectMappingProvider *mappingProvider = [RKObjectMappingProvider mappingProvider]; RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSMutableArray class]]; [mappingProvider setMapping:mapping forPattern:@"/articles/:id" context:1]; - RKObjectMappingDefinition * matchedMapping = [mappingProvider mappingForPatternMatchingString:@"/articles/12345?page=5&this=that" context:1]; + RKObjectMappingDefinition *matchedMapping = [mappingProvider mappingForPatternMatchingString:@"/articles/12345?page=5&this=that" context:1]; assertThat(matchedMapping, is(equalTo(mapping))); } -- (void)testRetrievalOfMappingForPathMatcherWithMultipleEntries { +- (void)testRetrievalOfMappingForPathMatcherWithMultipleEntries +{ RKObjectMappingProvider *mappingProvider = [RKObjectMappingProvider mappingProvider]; RKObjectMapping *mapping_2 = [RKObjectMapping mappingForClass:[NSMutableArray class]]; @@ -236,7 +258,8 @@ - (void)testRetrievalOfMappingForPathMatcherWithMultipleEntries { assertThat([mappingProvider mappingForPatternMatchingString:@"/articles/12345/comments/3" context:1], is(equalTo(mapping_4))); } -- (void)testRetrievalOfMappingForPathMatcherWithEntriesInsertedByIndex { +- (void)testRetrievalOfMappingForPathMatcherWithEntriesInsertedByIndex +{ RKObjectMappingProvider *mappingProvider = [RKObjectMappingProvider mappingProvider]; RKObjectMapping *mapping_2 = [RKObjectMapping mappingForClass:[NSMutableArray class]]; @@ -258,7 +281,8 @@ - (void)testRetrievalOfMappingForPathMatcherWithEntriesInsertedByIndex { assertThat([mappingProvider mappingForPatternMatchingString:@"/articles/12345/comments/3" context:1], is(equalTo(mapping_4))); } -- (void)testRetrievalOfEntryForPathMatcher { +- (void)testRetrievalOfEntryForPathMatcher +{ RKObjectMappingProvider *mappingProvider = [RKObjectMappingProvider mappingProvider]; RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSMutableArray class]]; RKObjectMappingProviderContextEntry *entry = [RKObjectMappingProviderContextEntry contextEntryWithMapping:mapping]; @@ -269,7 +293,8 @@ - (void)testRetrievalOfEntryForPathMatcher { assertThat(matchingEntry, is(equalTo(entry))); } -- (void)testRetrievalOfEntryForPathMatcherIncludingQueryParameters { +- (void)testRetrievalOfEntryForPathMatcherIncludingQueryParameters +{ RKObjectMappingProvider *mappingProvider = [RKObjectMappingProvider mappingProvider]; RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSMutableArray class]]; RKObjectMappingProviderContextEntry *entry = [RKObjectMappingProviderContextEntry contextEntryWithMapping:mapping]; diff --git a/Tests/Logic/ObjectMapping/RKObjectMappingResultTest.m b/Tests/Logic/ObjectMapping/RKObjectMappingResultTest.m index 3c46723788..1469865ad1 100644 --- a/Tests/Logic/ObjectMapping/RKObjectMappingResultTest.m +++ b/Tests/Logic/ObjectMapping/RKObjectMappingResultTest.m @@ -27,9 +27,10 @@ @interface RKObjectMappingResultTest : RKTestCase @implementation RKObjectMappingResultTest -- (void)testShouldNotCrashWhenAsObjectIsInvokedOnAnEmptyResult { - NSException* exception = nil; - RKObjectMappingResult* result = [RKObjectMappingResult mappingResultWithDictionary:[NSDictionary dictionary]]; +- (void)testShouldNotCrashWhenAsObjectIsInvokedOnAnEmptyResult +{ + NSException *exception = nil; + RKObjectMappingResult *result = [RKObjectMappingResult mappingResultWithDictionary:[NSDictionary dictionary]]; @try { [result asObject]; } @@ -41,14 +42,16 @@ - (void)testShouldNotCrashWhenAsObjectIsInvokedOnAnEmptyResult { } } -- (void)testShouldReturnNilForAnEmptyCollectionCoercedToAsObject { - RKObjectMappingResult* result = [RKObjectMappingResult mappingResultWithDictionary:[NSDictionary dictionary]]; +- (void)testShouldReturnNilForAnEmptyCollectionCoercedToAsObject +{ + RKObjectMappingResult *result = [RKObjectMappingResult mappingResultWithDictionary:[NSDictionary dictionary]]; assertThat([result asObject], is(equalTo(nil))); } -- (void)testShouldReturnTheFirstObjectInTheCollectionWhenCoercedToAsObject { - NSDictionary* dictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"one", @"one", @"two", @"two", nil]; - RKObjectMappingResult* result = [RKObjectMappingResult mappingResultWithDictionary:dictionary]; +- (void)testShouldReturnTheFirstObjectInTheCollectionWhenCoercedToAsObject +{ + NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"one", @"one", @"two", @"two", nil]; + RKObjectMappingResult *result = [RKObjectMappingResult mappingResultWithDictionary:dictionary]; assertThat([result asObject], is(equalTo(@"one"))); } diff --git a/Tests/Logic/ObjectMapping/RKObjectPaginatorTest.m b/Tests/Logic/ObjectMapping/RKObjectPaginatorTest.m index 09b0b16e19..b0f5b13417 100644 --- a/Tests/Logic/ObjectMapping/RKObjectPaginatorTest.m +++ b/Tests/Logic/ObjectMapping/RKObjectPaginatorTest.m @@ -54,11 +54,13 @@ @implementation RKTestPaginatorDelegate @synthesize loading; @synthesize timeout; -+ (RKTestPaginatorDelegate *)paginatorDelegate { ++ (RKTestPaginatorDelegate *)paginatorDelegate +{ return [[self new] autorelease]; } -- (id)init { +- (id)init +{ self = [super init]; if (self) { currentPage = NSIntegerMax; @@ -68,27 +70,31 @@ - (id)init { return self; } -- (void)dealloc { +- (void)dealloc +{ [paginatedObjects release]; [paginationError release]; [super dealloc]; } -- (BOOL)isLoaded { +- (BOOL)isLoaded +{ return currentPage != NSIntegerMax; } -- (BOOL)isError { +- (BOOL)isError +{ return paginationError == nil; } -- (void)waitForLoad { +- (void)waitForLoad +{ loading = YES; self.paginatedObjects = nil; self.paginationError = nil; - NSDate* startDate = [NSDate date]; + NSDate *startDate = [NSDate date]; while (loading) { [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; @@ -101,26 +107,31 @@ - (void)waitForLoad { #pragma mark - RKObjectPaginatorDelegate -- (void)paginator:(RKObjectPaginator *)paginator didLoadObjects:(NSArray *)objects forPage:(NSUInteger)page { +- (void)paginator:(RKObjectPaginator *)paginator didLoadObjects:(NSArray *)objects forPage:(NSUInteger)page +{ loading = NO; self.paginatedObjects = objects; currentPage = page; } -- (void)paginator:(RKObjectPaginator *)paginator didFailWithError:(NSError *)error objectLoader:(RKObjectLoader *)loader { +- (void)paginator:(RKObjectPaginator *)paginator didFailWithError:(NSError *)error objectLoader:(RKObjectLoader *)loader +{ loading = NO; self.paginationError = error; } -- (void)paginator:(RKObjectPaginator *)paginator willLoadPage:(NSUInteger)page objectLoader:(RKObjectLoader *)loader { +- (void)paginator:(RKObjectPaginator *)paginator willLoadPage:(NSUInteger)page objectLoader:(RKObjectLoader *)loader +{ // Necessary for OCMock expectations } -- (void)paginatorDidLoadFirstPage:(RKObjectPaginator *)paginator { +- (void)paginatorDidLoadFirstPage:(RKObjectPaginator *)paginator +{ // Necessary for OCMock expectations } -- (void)paginatorDidLoadLastPage:(RKObjectPaginator *)paginator { +- (void)paginatorDidLoadLastPage:(RKObjectPaginator *)paginator +{ // Necessary for OCMock expectations } @@ -135,15 +146,18 @@ @implementation RKObjectPaginatorTest static NSString * const RKObjectPaginatorTestResourcePathPattern = @"/paginate?per_page=:perPage&page=:currentPage"; -- (void)setUp { +- (void)setUp +{ [RKTestFactory setUp]; } -- (void)tearDown { +- (void)tearDown +{ [RKTestFactory tearDown]; } -- (RKObjectMappingProvider *)paginationMappingProvider { +- (RKObjectMappingProvider *)paginationMappingProvider +{ RKObjectMapping *paginationMapping = [RKObjectMapping mappingForClass:[RKObjectPaginator class]]; [paginationMapping mapKeyPath:@"current_page" toAttribute:@"currentPage"]; [paginationMapping mapKeyPath:@"per_page" toAttribute:@"perPage"]; @@ -158,32 +172,37 @@ - (RKObjectMappingProvider *)paginationMappingProvider { return mappingProvider; } -- (void)testInitCopiesPatternURL { +- (void)testInitCopiesPatternURL +{ RKURL *patternURL = [RKURL URLWithBaseURLString:@"http://restkit.org"]; RKObjectPaginator *paginator = [RKObjectPaginator paginatorWithPatternURL:patternURL mappingProvider:nil]; assertThat([paginator.patternURL absoluteString], is(equalTo(@"http://restkit.org"))); } -- (void)testInitRetainsMappingProvider { +- (void)testInitRetainsMappingProvider +{ RKURL *patternURL = [RKURL URLWithBaseURLString:@"http://restkit.org" resourcePath:RKObjectPaginatorTestResourcePathPattern]; RKObjectMappingProvider *mappingProvider = [self paginationMappingProvider]; RKObjectPaginator *paginator = [RKObjectPaginator paginatorWithPatternURL:patternURL mappingProvider:mappingProvider]; assertThat(paginator.mappingProvider, is(equalTo(mappingProvider))); } -- (void)testInitDoesNotHavePageCount { +- (void)testInitDoesNotHavePageCount +{ RKURL *patternURL = [RKURL URLWithBaseURLString:@"http://restkit.org" resourcePath:RKObjectPaginatorTestResourcePathPattern]; RKObjectPaginator *paginator = [RKObjectPaginator paginatorWithPatternURL:patternURL mappingProvider:nil]; assertThatBool([paginator hasPageCount], is(equalToBool(NO))); } -- (void)testInitDoesNotHaveObjectCount { +- (void)testInitDoesNotHaveObjectCount +{ RKURL *patternURL = [RKURL URLWithBaseURLString:@"http://restkit.org" resourcePath:RKObjectPaginatorTestResourcePathPattern]; RKObjectPaginator *paginator = [RKObjectPaginator paginatorWithPatternURL:patternURL mappingProvider:nil]; assertThatBool([paginator hasObjectCount], is(equalToBool(NO))); } -- (void)testThatLoadWithNilMappingProviderRaisesException { +- (void)testThatLoadWithNilMappingProviderRaisesException +{ RKURL *patternURL = [RKURL URLWithBaseURLString:@"http://restkit.org" resourcePath:RKObjectPaginatorTestResourcePathPattern]; RKObjectPaginator *paginator = [RKObjectPaginator paginatorWithPatternURL:patternURL mappingProvider:nil]; NSException *exception = nil; @@ -198,7 +217,8 @@ - (void)testThatLoadWithNilMappingProviderRaisesException { } } -- (void)testThatResourcePathPatternEvaluatesAgainstPaginator { +- (void)testThatResourcePathPatternEvaluatesAgainstPaginator +{ RKURL *patternURL = [RKURL URLWithBaseURLString:@"http://restkit.org" resourcePath:RKObjectPaginatorTestResourcePathPattern]; RKObjectPaginator *paginator = [RKObjectPaginator paginatorWithPatternURL:patternURL mappingProvider:nil]; id mockPaginator = [OCMockObject partialMockForObject:paginator]; @@ -207,7 +227,8 @@ - (void)testThatResourcePathPatternEvaluatesAgainstPaginator { assertThat([[paginator URL] resourcePath], is(equalTo(@"/paginate?per_page=25&page=1"))); } -- (void)testThatURLReturnsReflectsStateOfPaginator { +- (void)testThatURLReturnsReflectsStateOfPaginator +{ RKURL *patternURL = [RKURL URLWithBaseURLString:@"http://restkit.org" resourcePath:RKObjectPaginatorTestResourcePathPattern]; RKObjectPaginator *paginator = [RKObjectPaginator paginatorWithPatternURL:patternURL mappingProvider:nil]; id mockPaginator = [OCMockObject partialMockForObject:paginator]; @@ -219,7 +240,8 @@ - (void)testThatURLReturnsReflectsStateOfPaginator { assertThat([[mockPaginator URL] queryParameters], is(equalTo(queryParams))); } -- (void)testLoadingAPageOfObjects { +- (void)testLoadingAPageOfObjects +{ RKURL *patternURL = [[RKTestFactory baseURL] URLByAppendingResourcePath:RKObjectPaginatorTestResourcePathPattern]; RKObjectMappingProvider *mappingProvider = [self paginationMappingProvider]; RKTestPaginatorDelegate *testDelegate = [RKTestPaginatorDelegate paginatorDelegate]; @@ -230,7 +252,8 @@ - (void)testLoadingAPageOfObjects { assertThatBool([testDelegate isLoaded], is(equalToBool(YES))); } -- (void)testLoadingPageOfObjectMapsPerPage { +- (void)testLoadingPageOfObjectMapsPerPage +{ RKURL *patternURL = [[RKTestFactory baseURL] URLByAppendingResourcePath:RKObjectPaginatorTestResourcePathPattern]; RKObjectMappingProvider *mappingProvider = [self paginationMappingProvider]; RKObjectPaginator *paginator = [RKObjectPaginator paginatorWithPatternURL:patternURL mappingProvider:mappingProvider]; @@ -241,7 +264,8 @@ - (void)testLoadingPageOfObjectMapsPerPage { assertThatInteger(paginator.perPage, is(equalToInteger(3))); } -- (void)testLoadingPageOfObjectMapsTotalEntries { +- (void)testLoadingPageOfObjectMapsTotalEntries +{ RKURL *patternURL = [[RKTestFactory baseURL] URLByAppendingResourcePath:RKObjectPaginatorTestResourcePathPattern]; RKObjectMappingProvider *mappingProvider = [self paginationMappingProvider]; RKObjectPaginator *paginator = [RKObjectPaginator paginatorWithPatternURL:patternURL mappingProvider:mappingProvider]; @@ -252,7 +276,8 @@ - (void)testLoadingPageOfObjectMapsTotalEntries { assertThatInteger(paginator.objectCount, is(equalToInteger(6))); } -- (void)testLoadingPageOfObjectMapsCurrentPage { +- (void)testLoadingPageOfObjectMapsCurrentPage +{ RKURL *patternURL = [[RKTestFactory baseURL] URLByAppendingResourcePath:RKObjectPaginatorTestResourcePathPattern]; RKObjectMappingProvider *mappingProvider = [self paginationMappingProvider]; RKObjectPaginator *paginator = [RKObjectPaginator paginatorWithPatternURL:patternURL mappingProvider:mappingProvider]; @@ -263,7 +288,8 @@ - (void)testLoadingPageOfObjectMapsCurrentPage { assertThatInteger(paginator.currentPage, is(equalToInteger(1))); } -- (void)testLoadingPageOfObjectMapsEntriesToObjects { +- (void)testLoadingPageOfObjectMapsEntriesToObjects +{ RKURL *patternURL = [[RKTestFactory baseURL] URLByAppendingResourcePath:RKObjectPaginatorTestResourcePathPattern]; RKObjectMappingProvider *mappingProvider = [self paginationMappingProvider]; RKObjectPaginator *paginator = [RKObjectPaginator paginatorWithPatternURL:patternURL mappingProvider:mappingProvider]; @@ -275,7 +301,8 @@ - (void)testLoadingPageOfObjectMapsEntriesToObjects { assertThat([[testDelegate paginatedObjects] valueForKey:@"name"], is(equalTo([NSArray arrayWithObjects:@"Blake", @"Sarah", @"Colin", nil]))); } -- (void)testLoadingPageOfObjectHasPageCount { +- (void)testLoadingPageOfObjectHasPageCount +{ RKURL *patternURL = [[RKTestFactory baseURL] URLByAppendingResourcePath:RKObjectPaginatorTestResourcePathPattern]; RKObjectMappingProvider *mappingProvider = [self paginationMappingProvider]; RKObjectPaginator *paginator = [RKObjectPaginator paginatorWithPatternURL:patternURL mappingProvider:mappingProvider]; @@ -286,7 +313,8 @@ - (void)testLoadingPageOfObjectHasPageCount { assertThatBool([paginator hasPageCount], is(equalToBool(YES))); } -- (void)testLoadingPageOfObjectHasObjectCount { +- (void)testLoadingPageOfObjectHasObjectCount +{ RKURL *patternURL = [[RKTestFactory baseURL] URLByAppendingResourcePath:RKObjectPaginatorTestResourcePathPattern]; RKObjectMappingProvider *mappingProvider = [self paginationMappingProvider]; RKObjectPaginator *paginator = [RKObjectPaginator paginatorWithPatternURL:patternURL mappingProvider:mappingProvider]; @@ -297,7 +325,8 @@ - (void)testLoadingPageOfObjectHasObjectCount { assertThatBool([paginator hasObjectCount], is(equalToBool(YES))); } -- (void)testOnDidLoadObjectsForPageBlockIsInvokedOnLoad { +- (void)testOnDidLoadObjectsForPageBlockIsInvokedOnLoad +{ RKURL *patternURL = [[RKTestFactory baseURL] URLByAppendingResourcePath:RKObjectPaginatorTestResourcePathPattern]; RKObjectMappingProvider *mappingProvider = [self paginationMappingProvider]; RKObjectPaginator *paginator = [RKObjectPaginator paginatorWithPatternURL:patternURL mappingProvider:mappingProvider]; @@ -312,7 +341,8 @@ - (void)testOnDidLoadObjectsForPageBlockIsInvokedOnLoad { assertThat(blockObjects, is(notNilValue())); } -- (void)testDelegateIsInformedOfWillLoadPage { +- (void)testDelegateIsInformedOfWillLoadPage +{ RKURL *patternURL = [[RKTestFactory baseURL] URLByAppendingResourcePath:RKObjectPaginatorTestResourcePathPattern]; RKObjectMappingProvider *mappingProvider = [self paginationMappingProvider]; RKObjectPaginator *paginator = [RKObjectPaginator paginatorWithPatternURL:patternURL mappingProvider:mappingProvider]; @@ -325,7 +355,8 @@ - (void)testDelegateIsInformedOfWillLoadPage { [mockDelegate verify]; } -- (void)testDelegateIsInformedOnError { +- (void)testDelegateIsInformedOnError +{ RKURL *patternURL = [[RKTestFactory baseURL] URLByAppendingResourcePath:RKObjectPaginatorTestResourcePathPattern]; RKObjectMappingProvider *mappingProvider = [self paginationMappingProvider]; RKObjectPaginator *paginator = [RKObjectPaginator paginatorWithPatternURL:patternURL mappingProvider:mappingProvider]; @@ -338,7 +369,8 @@ - (void)testDelegateIsInformedOnError { [mockDelegate verify]; } -- (void)testOnDidFailWithErrorBlockIsInvokedOnError { +- (void)testOnDidFailWithErrorBlockIsInvokedOnError +{ RKURL *patternURL = [[RKTestFactory baseURL] URLByAppendingResourcePath:RKObjectPaginatorTestResourcePathPattern]; RKObjectMappingProvider *mappingProvider = [self paginationMappingProvider]; RKObjectPaginator *paginator = [RKObjectPaginator paginatorWithPatternURL:patternURL mappingProvider:mappingProvider]; @@ -353,7 +385,8 @@ - (void)testOnDidFailWithErrorBlockIsInvokedOnError { assertThat(expectedError, is(notNilValue())); } -- (void)testDelegateIsInformedOnLoadOfFirstPage { +- (void)testDelegateIsInformedOnLoadOfFirstPage +{ RKURL *patternURL = [[RKTestFactory baseURL] URLByAppendingResourcePath:RKObjectPaginatorTestResourcePathPattern]; RKObjectMappingProvider *mappingProvider = [self paginationMappingProvider]; RKObjectPaginator *paginator = [RKObjectPaginator paginatorWithPatternURL:patternURL mappingProvider:mappingProvider]; @@ -366,7 +399,8 @@ - (void)testDelegateIsInformedOnLoadOfFirstPage { [mockDelegate verify]; } -- (void)testDelegateIsInformedOnLoadOfLastPage { +- (void)testDelegateIsInformedOnLoadOfLastPage +{ RKURL *patternURL = [[RKTestFactory baseURL] URLByAppendingResourcePath:RKObjectPaginatorTestResourcePathPattern]; RKObjectMappingProvider *mappingProvider = [self paginationMappingProvider]; RKObjectPaginator *paginator = [RKObjectPaginator paginatorWithPatternURL:patternURL mappingProvider:mappingProvider]; @@ -379,7 +413,8 @@ - (void)testDelegateIsInformedOnLoadOfLastPage { [mockDelegate verify]; } -- (void)testLoadingNextPageOfObjects { +- (void)testLoadingNextPageOfObjects +{ RKURL *patternURL = [[RKTestFactory baseURL] URLByAppendingResourcePath:RKObjectPaginatorTestResourcePathPattern]; RKObjectMappingProvider *mappingProvider = [self paginationMappingProvider]; RKObjectPaginator *paginator = [RKObjectPaginator paginatorWithPatternURL:patternURL mappingProvider:mappingProvider]; @@ -394,7 +429,8 @@ - (void)testLoadingNextPageOfObjects { assertThat([[testDelegate paginatedObjects] valueForKey:@"name"], is(equalTo([NSArray arrayWithObjects:@"Asia", @"Roy", @"Lola", nil]))); } -- (void)testLoadingPreviousPageOfObjects { +- (void)testLoadingPreviousPageOfObjects +{ RKURL *patternURL = [[RKTestFactory baseURL] URLByAppendingResourcePath:RKObjectPaginatorTestResourcePathPattern]; RKObjectMappingProvider *mappingProvider = [self paginationMappingProvider]; RKObjectPaginator *paginator = [RKObjectPaginator paginatorWithPatternURL:patternURL mappingProvider:mappingProvider]; @@ -409,7 +445,8 @@ - (void)testLoadingPreviousPageOfObjects { assertThat([[testDelegate paginatedObjects] valueForKey:@"name"], is(equalTo([NSArray arrayWithObjects:@"Blake", @"Sarah", @"Colin", nil]))); } -- (void)testFailureWhenLoadingAPageOfObjects { +- (void)testFailureWhenLoadingAPageOfObjects +{ RKURL *patternURL = [[RKTestFactory baseURL] URLByAppendingResourcePath:RKObjectPaginatorTestResourcePathPattern]; RKObjectMappingProvider *mappingProvider = [self paginationMappingProvider]; RKObjectPaginator *paginator = [RKObjectPaginator paginatorWithPatternURL:patternURL mappingProvider:mappingProvider]; @@ -420,7 +457,8 @@ - (void)testFailureWhenLoadingAPageOfObjects { assertThat(testDelegate.paginationError, is(notNilValue())); } -- (void)testKnowledgeOfHasANextPage { +- (void)testKnowledgeOfHasANextPage +{ RKObjectPaginator *paginator = [[RKObjectPaginator new] autorelease]; id mockPaginator = [OCMockObject partialMockForObject:paginator]; BOOL isLoaded = YES; @@ -441,7 +479,8 @@ - (void)testKnowledgeOfHasANextPage { assertThatBool([mockPaginator hasNextPage], is(equalToBool(NO))); } -- (void)testHasNextPageRaisesExpectionWhenNotLoaded { +- (void)testHasNextPageRaisesExpectionWhenNotLoaded +{ RKObjectPaginator *paginator = [[RKObjectPaginator new] autorelease]; id mockPaginator = [OCMockObject partialMockForObject:paginator]; BOOL loaded = NO; @@ -449,7 +488,8 @@ - (void)testHasNextPageRaisesExpectionWhenNotLoaded { STAssertThrows([mockPaginator hasNextPage], @"Expected exception due to isLoaded == NO"); } -- (void)testHasNextPageRaisesExpectionWhenPageCountIsUnknown { +- (void)testHasNextPageRaisesExpectionWhenPageCountIsUnknown +{ RKObjectPaginator *paginator = [[RKObjectPaginator new] autorelease]; id mockPaginator = [OCMockObject partialMockForObject:paginator]; BOOL loaded = YES; @@ -459,7 +499,8 @@ - (void)testHasNextPageRaisesExpectionWhenPageCountIsUnknown { STAssertThrows([mockPaginator hasNextPage], @"Expected exception due to pageCount == NSUIntegerMax"); } -- (void)testHasPreviousPageRaisesExpectionWhenNotLoaded { +- (void)testHasPreviousPageRaisesExpectionWhenNotLoaded +{ RKObjectPaginator *paginator = [[RKObjectPaginator new] autorelease]; id mockPaginator = [OCMockObject partialMockForObject:paginator]; BOOL loaded = NO; @@ -467,7 +508,8 @@ - (void)testHasPreviousPageRaisesExpectionWhenNotLoaded { STAssertThrows([mockPaginator hasPreviousPage], @"Expected exception due to isLoaded == NO"); } -- (void)testKnowledgeOfPreviousPage { +- (void)testKnowledgeOfPreviousPage +{ RKObjectPaginator *paginator = [[RKObjectPaginator new] autorelease]; id mockPaginator = [OCMockObject partialMockForObject:paginator]; BOOL isLoaded = YES; diff --git a/Tests/Logic/ObjectMapping/RKObjectRouterTest.m b/Tests/Logic/ObjectMapping/RKObjectRouterTest.m index 328e164588..3d09b61149 100644 --- a/Tests/Logic/ObjectMapping/RKObjectRouterTest.m +++ b/Tests/Logic/ObjectMapping/RKObjectRouterTest.m @@ -26,7 +26,8 @@ @interface RKTestObject : NSObject @end @implementation RKTestObject -+ (id)object { ++ (id)object +{ return [[self new] autorelease]; } @end @@ -43,7 +44,8 @@ @interface RKObjectRouterTest : RKTestCase { @implementation RKTestUser (PolymorphicResourcePath) -- (NSString *)polymorphicResourcePath { +- (NSString *)polymorphicResourcePath +{ return @"/this/is/the/path"; } @@ -51,69 +53,76 @@ - (NSString *)polymorphicResourcePath { @implementation RKObjectRouterTest --(void)testThrowAnExceptionWhenAskedForAPathForAnUnregisteredClassAndMethod { - RKObjectRouter* router = [[[RKObjectRouter alloc] init] autorelease]; - NSException* exception = nil; +- (void)testThrowAnExceptionWhenAskedForAPathForAnUnregisteredClassAndMethod +{ + RKObjectRouter *router = [[[RKObjectRouter alloc] init] autorelease]; + NSException *exception = nil; @try { [router resourcePathForObject:[RKTestObject object] method:RKRequestMethodPOST]; } - @catch (NSException * e) { + @catch (NSException *e) { exception = e; } assertThat(exception, isNot(nilValue())); } --(void)testThrowAnExceptionWhenAskedForAPathForARegisteredClassButUnregisteredMethod { - RKObjectRouter* router = [[[RKObjectRouter alloc] init] autorelease]; +- (void)testThrowAnExceptionWhenAskedForAPathForARegisteredClassButUnregisteredMethod +{ + RKObjectRouter *router = [[[RKObjectRouter alloc] init] autorelease]; [router routeClass:[RKTestObject class] toResourcePath:@"/HumanService.asp" forMethod:RKRequestMethodGET]; - NSException* exception = nil; + NSException *exception = nil; @try { [router resourcePathForObject:[RKTestObject object] method:RKRequestMethodPOST]; } - @catch (NSException * e) { + @catch (NSException *e) { exception = e; } assertThat(exception, isNot(nilValue())); } --(void)testReturnPathsRegisteredForTestificRequestMethods { - RKObjectRouter* router = [[[RKObjectRouter alloc] init] autorelease]; +- (void)testReturnPathsRegisteredForTestificRequestMethods +{ + RKObjectRouter *router = [[[RKObjectRouter alloc] init] autorelease]; [router routeClass:[RKTestObject class] toResourcePath:@"/HumanService.asp" forMethod:RKRequestMethodGET]; - NSString* path = [router resourcePathForObject:[RKTestObject object] method:RKRequestMethodGET]; + NSString *path = [router resourcePathForObject:[RKTestObject object] method:RKRequestMethodGET]; assertThat(path, is(equalTo(@"/HumanService.asp"))); } --(void)testReturnPathsRegisteredForTheClassAsAWhole { - RKObjectRouter* router = [[[RKObjectRouter alloc] init] autorelease]; +- (void)testReturnPathsRegisteredForTheClassAsAWhole +{ + RKObjectRouter *router = [[[RKObjectRouter alloc] init] autorelease]; [router routeClass:[RKTestObject class] toResourcePath:@"/HumanService.asp"]; - NSString* path = [router resourcePathForObject:[RKTestObject object] method:RKRequestMethodGET]; + NSString *path = [router resourcePathForObject:[RKTestObject object] method:RKRequestMethodGET]; assertThat(path, is(equalTo(@"/HumanService.asp"))); path = [router resourcePathForObject:[RKTestObject object] method:RKRequestMethodPOST]; assertThat(path, is(equalTo(@"/HumanService.asp"))); } -- (void)testShouldReturnPathsIfTheSuperclassIsRegistered { - RKObjectRouter* router = [[[RKObjectRouter alloc] init] autorelease]; +- (void)testShouldReturnPathsIfTheSuperclassIsRegistered +{ + RKObjectRouter *router = [[[RKObjectRouter alloc] init] autorelease]; [router routeClass:[RKTestObject class] toResourcePath:@"/HumanService.asp"]; - NSString* path = [router resourcePathForObject:[RKTestSubclassedObject new] method:RKRequestMethodGET]; + NSString *path = [router resourcePathForObject:[RKTestSubclassedObject new] method:RKRequestMethodGET]; assertThat(path, is(equalTo(@"/HumanService.asp"))); } -- (void)testShouldFavorExactMatcherOverSuperclassMatches { - RKObjectRouter* router = [[[RKObjectRouter alloc] init] autorelease]; +- (void)testShouldFavorExactMatcherOverSuperclassMatches +{ + RKObjectRouter *router = [[[RKObjectRouter alloc] init] autorelease]; [router routeClass:[RKTestObject class] toResourcePath:@"/HumanService.asp"]; [router routeClass:[RKTestSubclassedObject class] toResourcePath:@"/SubclassedHumanService.asp"]; - NSString* path = [router resourcePathForObject:[RKTestSubclassedObject new] method:RKRequestMethodGET]; + NSString *path = [router resourcePathForObject:[RKTestSubclassedObject new] method:RKRequestMethodGET]; assertThat(path, is(equalTo(@"/SubclassedHumanService.asp"))); path = [router resourcePathForObject:[RKTestObject new] method:RKRequestMethodPOST]; assertThat(path, is(equalTo(@"/HumanService.asp"))); } --(void)testFavorTestificMethodsWhenClassAndTestificMethodsAreRegistered { - RKObjectRouter* router = [[[RKObjectRouter alloc] init] autorelease]; +- (void)testFavorTestificMethodsWhenClassAndTestificMethodsAreRegistered +{ + RKObjectRouter *router = [[[RKObjectRouter alloc] init] autorelease]; [router routeClass:[RKTestObject class] toResourcePath:@"/HumanService.asp"]; [router routeClass:[RKTestObject class] toResourcePath:@"/HumanServiceForPUT.asp" forMethod:RKRequestMethodPUT]; - NSString* path = [router resourcePathForObject:[RKTestObject object] method:RKRequestMethodGET]; + NSString *path = [router resourcePathForObject:[RKTestObject object] method:RKRequestMethodGET]; assertThat(path, is(equalTo(@"/HumanService.asp"))); path = [router resourcePathForObject:[RKTestObject object] method:RKRequestMethodPOST]; assertThat(path, is(equalTo(@"/HumanService.asp"))); @@ -121,60 +130,65 @@ -(void)testFavorTestificMethodsWhenClassAndTestificMethodsAreRegistered { assertThat(path, is(equalTo(@"/HumanServiceForPUT.asp"))); } --(void)testRaiseAnExceptionWhenAttemptIsMadeToRegisterOverAnExistingRoute { - RKObjectRouter* router = [[[RKObjectRouter alloc] init] autorelease]; +- (void)testRaiseAnExceptionWhenAttemptIsMadeToRegisterOverAnExistingRoute +{ + RKObjectRouter *router = [[[RKObjectRouter alloc] init] autorelease]; [router routeClass:[RKTestObject class] toResourcePath:@"/HumanService.asp" forMethod:RKRequestMethodGET]; - NSException* exception = nil; + NSException *exception = nil; @try { [router routeClass:[RKTestObject class] toResourcePathPattern:@"/HumanService.asp" forMethod:RKRequestMethodGET]; } - @catch (NSException * e) { + @catch (NSException *e) { exception = e; } assertThat(exception, isNot(nilValue())); } -- (void)testShouldInterpolatePropertyNamesReferencedInTheMapping { - RKTestUser* blake = [RKTestUser user]; +- (void)testShouldInterpolatePropertyNamesReferencedInTheMapping +{ + RKTestUser *blake = [RKTestUser user]; blake.name = @"blake"; blake.userID = [NSNumber numberWithInt:31337]; - RKObjectRouter* router = [[[RKObjectRouter alloc] init] autorelease]; + RKObjectRouter *router = [[[RKObjectRouter alloc] init] autorelease]; [router routeClass:[RKTestUser class] toResourcePathPattern:@"/humans/:userID/:name" forMethod:RKRequestMethodGET]; - NSString* resourcePath = [router resourcePathForObject:blake method:RKRequestMethodGET]; + NSString *resourcePath = [router resourcePathForObject:blake method:RKRequestMethodGET]; assertThat(resourcePath, is(equalTo(@"/humans/31337/blake"))); } -- (void)testShouldInterpolatePropertyNamesReferencedInTheMappingWithDeprecatedParentheses { - RKTestUser* blake = [RKTestUser user]; +- (void)testShouldInterpolatePropertyNamesReferencedInTheMappingWithDeprecatedParentheses +{ + RKTestUser *blake = [RKTestUser user]; blake.name = @"blake"; blake.userID = [NSNumber numberWithInt:31337]; - RKObjectRouter* router = [[[RKObjectRouter alloc] init] autorelease]; + RKObjectRouter *router = [[[RKObjectRouter alloc] init] autorelease]; [router routeClass:[RKTestUser class] toResourcePathPattern:@"/humans/(userID)/(name)" forMethod:RKRequestMethodGET]; - NSString* resourcePath = [router resourcePathForObject:blake method:RKRequestMethodGET]; + NSString *resourcePath = [router resourcePathForObject:blake method:RKRequestMethodGET]; assertThat(resourcePath, is(equalTo(@"/humans/31337/blake"))); } -- (void)testShouldAllowForPolymorphicURLsViaMethodCalls { - RKTestUser* blake = [RKTestUser user]; +- (void)testShouldAllowForPolymorphicURLsViaMethodCalls +{ + RKTestUser *blake = [RKTestUser user]; blake.name = @"blake"; blake.userID = [NSNumber numberWithInt:31337]; - RKObjectRouter* router = [[[RKObjectRouter alloc] init] autorelease]; + RKObjectRouter *router = [[[RKObjectRouter alloc] init] autorelease]; [router routeClass:[RKTestUser class] toResourcePathPattern:@":polymorphicResourcePath" forMethod:RKRequestMethodGET escapeRoutedPath:NO]; - NSString* resourcePath = [router resourcePathForObject:blake method:RKRequestMethodGET]; + NSString *resourcePath = [router resourcePathForObject:blake method:RKRequestMethodGET]; assertThat(resourcePath, is(equalTo(@"/this/is/the/path"))); } -- (void)testShouldAllowForPolymorphicURLsViaMethodCallsWithDeprecatedParentheses { - RKTestUser* blake = [RKTestUser user]; +- (void)testShouldAllowForPolymorphicURLsViaMethodCallsWithDeprecatedParentheses +{ + RKTestUser *blake = [RKTestUser user]; blake.name = @"blake"; blake.userID = [NSNumber numberWithInt:31337]; - RKObjectRouter* router = [[[RKObjectRouter alloc] init] autorelease]; + RKObjectRouter *router = [[[RKObjectRouter alloc] init] autorelease]; [router routeClass:[RKTestUser class] toResourcePathPattern:@"(polymorphicResourcePath)" forMethod:RKRequestMethodGET escapeRoutedPath:NO]; - NSString* resourcePath = [router resourcePathForObject:blake method:RKRequestMethodGET]; + NSString *resourcePath = [router resourcePathForObject:blake method:RKRequestMethodGET]; assertThat(resourcePath, is(equalTo(@"/this/is/the/path"))); } diff --git a/Tests/Logic/ObjectMapping/RKObjectSerializerTest.m b/Tests/Logic/ObjectMapping/RKObjectSerializerTest.m index fc2bc65e7a..2a72061b66 100644 --- a/Tests/Logic/ObjectMapping/RKObjectSerializerTest.m +++ b/Tests/Logic/ObjectMapping/RKObjectSerializerTest.m @@ -29,108 +29,114 @@ @interface RKObjectSerializerTest : RKTestCase { @implementation RKObjectSerializerTest -- (void)testShouldSerializeToFormEncodedData { - NSDictionary* object = [NSDictionary dictionaryWithObjectsAndKeys:@"value1", @"key1", @"value2", @"key2", nil]; - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[NSDictionary class]]; +- (void)testShouldSerializeToFormEncodedData +{ + NSDictionary *object = [NSDictionary dictionaryWithObjectsAndKeys:@"value1", @"key1", @"value2", @"key2", nil]; + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSDictionary class]]; [mapping addAttributeMapping:[RKObjectAttributeMapping mappingFromKeyPath:@"key1" toKeyPath:@"key1-form-name"]]; [mapping addAttributeMapping:[RKObjectAttributeMapping mappingFromKeyPath:@"key2" toKeyPath:@"key2-form-name"]]; - RKObjectSerializer* serializer = [RKObjectSerializer serializerWithObject:object mapping:mapping]; - NSError* error = nil; + RKObjectSerializer *serializer = [RKObjectSerializer serializerWithObject:object mapping:mapping]; + NSError *error = nil; id serialization = [serializer serializationForMIMEType:@"application/x-www-form-urlencoded" error:&error]; - NSString* data = [[[NSString alloc] initWithData:[serialization HTTPBody] encoding:NSUTF8StringEncoding] autorelease]; + NSString *data = [[[NSString alloc] initWithData:[serialization HTTPBody] encoding:NSUTF8StringEncoding] autorelease]; data = [data stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; assertThat(error, is(nilValue())); assertThat(data, is(equalTo(@"key2-form-name=value2&key1-form-name=value1"))); } -- (void)testShouldSerializeADateToFormEncodedData { - NSDictionary* object = [NSDictionary dictionaryWithObjectsAndKeys:@"value1", @"key1", [NSDate dateWithTimeIntervalSince1970:0], @"date", nil]; - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[NSDictionary class]]; +- (void)testShouldSerializeADateToFormEncodedData +{ + NSDictionary *object = [NSDictionary dictionaryWithObjectsAndKeys:@"value1", @"key1", [NSDate dateWithTimeIntervalSince1970:0], @"date", nil]; + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSDictionary class]]; [mapping addAttributeMapping:[RKObjectAttributeMapping mappingFromKeyPath:@"key1" toKeyPath:@"key1-form-name"]]; [mapping addAttributeMapping:[RKObjectAttributeMapping mappingFromKeyPath:@"date" toKeyPath:@"date-form-name"]]; - RKObjectSerializer* serializer = [RKObjectSerializer serializerWithObject:object mapping:mapping]; - NSError* error = nil; + RKObjectSerializer *serializer = [RKObjectSerializer serializerWithObject:object mapping:mapping]; + NSError *error = nil; id serialization = [serializer serializationForMIMEType:@"application/x-www-form-urlencoded" error:&error]; - NSString* data = [[[NSString alloc] initWithData:[serialization HTTPBody] encoding:NSUTF8StringEncoding] autorelease]; + NSString *data = [[[NSString alloc] initWithData:[serialization HTTPBody] encoding:NSUTF8StringEncoding] autorelease]; data = [data stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; assertThat(error, is(nilValue())); assertThat(data, is(equalTo(@"key1-form-name=value1&date-form-name=1970-01-01 00:00:00 +0000"))); } -- (void)testShouldSerializeADateToAStringUsingThePreferredDateFormatter { - NSDictionary* object = [NSDictionary dictionaryWithObjectsAndKeys:@"value1", @"key1", [NSDate dateWithTimeIntervalSince1970:0], @"date", nil]; - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[NSDictionary class]]; +- (void)testShouldSerializeADateToAStringUsingThePreferredDateFormatter +{ + NSDictionary *object = [NSDictionary dictionaryWithObjectsAndKeys:@"value1", @"key1", [NSDate dateWithTimeIntervalSince1970:0], @"date", nil]; + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSDictionary class]]; NSDateFormatter *dateFormatter = [[NSDateFormatter new] autorelease]; dateFormatter.dateFormat = @"MM/dd/yyyy"; dateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0]; mapping.preferredDateFormatter = dateFormatter; [mapping addAttributeMapping:[RKObjectAttributeMapping mappingFromKeyPath:@"key1" toKeyPath:@"key1-form-name"]]; [mapping addAttributeMapping:[RKObjectAttributeMapping mappingFromKeyPath:@"date" toKeyPath:@"date-form-name"]]; - RKObjectSerializer* serializer = [RKObjectSerializer serializerWithObject:object mapping:mapping]; - NSError* error = nil; + RKObjectSerializer *serializer = [RKObjectSerializer serializerWithObject:object mapping:mapping]; + NSError *error = nil; id serialization = [serializer serializationForMIMEType:@"application/x-www-form-urlencoded" error:&error]; - NSString* data = [[[NSString alloc] initWithData:[serialization HTTPBody] encoding:NSUTF8StringEncoding] autorelease]; + NSString *data = [[[NSString alloc] initWithData:[serialization HTTPBody] encoding:NSUTF8StringEncoding] autorelease]; data = [data stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; assertThat(error, is(nilValue())); assertThat(data, is(equalTo(@"key1-form-name=value1&date-form-name=01/01/1970"))); } -- (void)testShouldSerializeADateToJSON { - NSDictionary* object = [NSDictionary dictionaryWithObjectsAndKeys:@"value1", @"key1", [NSDate dateWithTimeIntervalSince1970:0], @"date", nil]; - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[NSDictionary class]]; +- (void)testShouldSerializeADateToJSON +{ + NSDictionary *object = [NSDictionary dictionaryWithObjectsAndKeys:@"value1", @"key1", [NSDate dateWithTimeIntervalSince1970:0], @"date", nil]; + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSDictionary class]]; [mapping addAttributeMapping:[RKObjectAttributeMapping mappingFromKeyPath:@"key1" toKeyPath:@"key1-form-name"]]; [mapping addAttributeMapping:[RKObjectAttributeMapping mappingFromKeyPath:@"date" toKeyPath:@"date-form-name"]]; - RKObjectSerializer* serializer = [RKObjectSerializer serializerWithObject:object mapping:mapping]; + RKObjectSerializer *serializer = [RKObjectSerializer serializerWithObject:object mapping:mapping]; - NSError* error = nil; + NSError *error = nil; id serialization = [serializer serializationForMIMEType:@"application/json" error:&error]; - NSString* data = [[[NSString alloc] initWithData:[serialization HTTPBody] encoding:NSUTF8StringEncoding] autorelease]; + NSString *data = [[[NSString alloc] initWithData:[serialization HTTPBody] encoding:NSUTF8StringEncoding] autorelease]; data = [data stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; assertThat(error, is(nilValue())); assertThat(data, is(equalTo(@"{\"key1-form-name\":\"value1\",\"date-form-name\":\"1970-01-01 00:00:00 +0000\"}"))); } -- (void)testShouldSerializeNSDecimalNumberAttributesToJSON { - NSDictionary* object = [NSDictionary dictionaryWithObjectsAndKeys:@"value1", @"key1", [NSDecimalNumber decimalNumberWithString:@"18274191731731.4557723623"], @"number", nil]; - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[NSDictionary class]]; +- (void)testShouldSerializeNSDecimalNumberAttributesToJSON +{ + NSDictionary *object = [NSDictionary dictionaryWithObjectsAndKeys:@"value1", @"key1", [NSDecimalNumber decimalNumberWithString:@"18274191731731.4557723623"], @"number", nil]; + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSDictionary class]]; [mapping addAttributeMapping:[RKObjectAttributeMapping mappingFromKeyPath:@"key1" toKeyPath:@"key1-form-name"]]; [mapping addAttributeMapping:[RKObjectAttributeMapping mappingFromKeyPath:@"number" toKeyPath:@"number-form-name"]]; - RKObjectSerializer* serializer = [RKObjectSerializer serializerWithObject:object mapping:mapping]; + RKObjectSerializer *serializer = [RKObjectSerializer serializerWithObject:object mapping:mapping]; - NSError* error = nil; + NSError *error = nil; id serialization = [serializer serializationForMIMEType:@"application/json" error:&error]; - NSString* data = [[[NSString alloc] initWithData:[serialization HTTPBody] encoding:NSUTF8StringEncoding] autorelease]; + NSString *data = [[[NSString alloc] initWithData:[serialization HTTPBody] encoding:NSUTF8StringEncoding] autorelease]; data = [data stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; assertThat(error, is(nilValue())); assertThat(data, is(equalTo(@"{\"key1-form-name\":\"value1\",\"number-form-name\":\"18274191731731.4557723623\"}"))); } -- (void)testShouldSerializeRelationshipsToo { - NSDictionary* object = [NSDictionary dictionaryWithObjectsAndKeys:@"value1", @"key1", @"value2", @"key2", +- (void)testShouldSerializeRelationshipsToo +{ + NSDictionary *object = [NSDictionary dictionaryWithObjectsAndKeys:@"value1", @"key1", @"value2", @"key2", [NSArray arrayWithObjects: [NSDictionary dictionaryWithObjectsAndKeys:@"relationship1Value1", @"relatioship1Key1", nil], [NSDictionary dictionaryWithObjectsAndKeys:@"relationship1Value2", @"relatioship1Key1", nil], nil], @"relationship1", [NSDictionary dictionaryWithObjectsAndKeys:@"subValue1", @"subKey1", nil], @"relationship2", nil]; - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; [mapping addAttributeMapping:[RKObjectAttributeMapping mappingFromKeyPath:@"key1" toKeyPath:@"key1-form-name"]]; [mapping addAttributeMapping:[RKObjectAttributeMapping mappingFromKeyPath:@"key2" toKeyPath:@"key2-form-name"]]; [mapping addAttributeMapping:[RKObjectAttributeMapping mappingFromKeyPath:@"relationship1.relatioship1Key1" toKeyPath:@"relationship1-form-name[r1k1]"]]; [mapping addAttributeMapping:[RKObjectAttributeMapping mappingFromKeyPath:@"relationship2.subKey1" toKeyPath:@"relationship2-form-name[subKey1]"]]; - RKObjectSerializer* serializer = [RKObjectSerializer serializerWithObject:object mapping:mapping]; - NSError* error = nil; + RKObjectSerializer *serializer = [RKObjectSerializer serializerWithObject:object mapping:mapping]; + NSError *error = nil; id serialization = [serializer serializationForMIMEType:@"application/x-www-form-urlencoded" error:&error]; - NSString* data = [[[NSString alloc] initWithData:[serialization HTTPBody] encoding:NSUTF8StringEncoding] autorelease]; + NSString *data = [[[NSString alloc] initWithData:[serialization HTTPBody] encoding:NSUTF8StringEncoding] autorelease]; data = [data stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; assertThat(error, is(nilValue())); @@ -141,53 +147,56 @@ - (void)testShouldSerializeRelationshipsToo { #endif } -- (void)testShouldSerializeToJSON { - NSDictionary* object = [NSDictionary dictionaryWithObjectsAndKeys:@"value1", @"key1", @"value2", @"key2", nil]; - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[NSDictionary class]]; +- (void)testShouldSerializeToJSON +{ + NSDictionary *object = [NSDictionary dictionaryWithObjectsAndKeys:@"value1", @"key1", @"value2", @"key2", nil]; + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSDictionary class]]; [mapping addAttributeMapping:[RKObjectAttributeMapping mappingFromKeyPath:@"key1" toKeyPath:@"key1-form-name"]]; [mapping addAttributeMapping:[RKObjectAttributeMapping mappingFromKeyPath:@"key2" toKeyPath:@"key2-form-name"]]; - RKObjectSerializer* serializer = [RKObjectSerializer serializerWithObject:object mapping:mapping]; - NSError* error = nil; + RKObjectSerializer *serializer = [RKObjectSerializer serializerWithObject:object mapping:mapping]; + NSError *error = nil; id serialization = [serializer serializationForMIMEType:@"application/json" error:&error]; - NSString* data = [[[NSString alloc] initWithData:[serialization HTTPBody] encoding:NSUTF8StringEncoding] autorelease]; + NSString *data = [[[NSString alloc] initWithData:[serialization HTTPBody] encoding:NSUTF8StringEncoding] autorelease]; data = [data stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; assertThat(error, is(nilValue())); assertThat(data, is(equalTo(@"{\"key2-form-name\":\"value2\",\"key1-form-name\":\"value1\"}"))); } -- (void)testShouldSetReturnNilIfItDoesNotFindAnythingToSerialize { - NSDictionary* object = [NSDictionary dictionaryWithObjectsAndKeys:@"value1", @"key1", @"value2", @"key2", nil]; - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[NSDictionary class]]; +- (void)testShouldSetReturnNilIfItDoesNotFindAnythingToSerialize +{ + NSDictionary *object = [NSDictionary dictionaryWithObjectsAndKeys:@"value1", @"key1", @"value2", @"key2", nil]; + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSDictionary class]]; [mapping addAttributeMapping:[RKObjectAttributeMapping mappingFromKeyPath:@"key12123" toKeyPath:@"key1-form-name"]]; - RKObjectSerializer* serializer = [RKObjectSerializer serializerWithObject:object mapping:mapping]; - NSError* error = nil; + RKObjectSerializer *serializer = [RKObjectSerializer serializerWithObject:object mapping:mapping]; + NSError *error = nil; id serialization = [serializer serializationForMIMEType:@"application/json" error:&error]; assertThat(serialization, is(nilValue())); } -- (void)testShouldSerializeNestedObjectsContainingDatesToJSON { - RKMappableObject* object = [[RKMappableObject new] autorelease]; +- (void)testShouldSerializeNestedObjectsContainingDatesToJSON +{ + RKMappableObject *object = [[RKMappableObject new] autorelease]; object.stringTest = @"The string"; - RKMappableAssociation* association = [[RKMappableAssociation new] autorelease]; + RKMappableAssociation *association = [[RKMappableAssociation new] autorelease]; association.date = [NSDate dateWithTimeIntervalSince1970:0]; object.hasOne = association; // Setup object mappings - RKObjectMapping* objectMapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; + RKObjectMapping *objectMapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; [objectMapping mapAttributes:@"stringTest", nil]; - RKObjectMapping* relationshipMapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; + RKObjectMapping *relationshipMapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; [relationshipMapping mapAttributes:@"date", nil]; [objectMapping mapRelationship:@"hasOne" withMapping:relationshipMapping]; // Serialize - RKObjectSerializer* serializer = [RKObjectSerializer serializerWithObject:object mapping:objectMapping]; - NSError* error = nil; + RKObjectSerializer *serializer = [RKObjectSerializer serializerWithObject:object mapping:objectMapping]; + NSError *error = nil; id serialization = [serializer serializationForMIMEType:@"application/json" error:&error]; assertThat(error, is(nilValue())); - NSString* data = [[[NSString alloc] initWithData:[serialization HTTPBody] encoding:NSUTF8StringEncoding] autorelease]; + NSString *data = [[[NSString alloc] initWithData:[serialization HTTPBody] encoding:NSUTF8StringEncoding] autorelease]; data = [data stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; // Encodes differently on iOS / OS X @@ -198,77 +207,81 @@ - (void)testShouldSerializeNestedObjectsContainingDatesToJSON { #endif } -- (void)testShouldEncloseTheSerializationInAContainerIfRequested { - NSDictionary* object = [NSDictionary dictionaryWithObjectsAndKeys:@"value1", @"key1", @"value2", @"key2", nil]; - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[NSDictionary class]]; +- (void)testShouldEncloseTheSerializationInAContainerIfRequested +{ + NSDictionary *object = [NSDictionary dictionaryWithObjectsAndKeys:@"value1", @"key1", @"value2", @"key2", nil]; + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSDictionary class]]; mapping.rootKeyPath = @"stuff"; [mapping addAttributeMapping:[RKObjectAttributeMapping mappingFromKeyPath:@"key1" toKeyPath:@"key1-form-name"]]; [mapping addAttributeMapping:[RKObjectAttributeMapping mappingFromKeyPath:@"key2" toKeyPath:@"key2-form-name"]]; - RKObjectSerializer* serializer = [RKObjectSerializer serializerWithObject:object mapping:mapping]; - NSError* error = nil; + RKObjectSerializer *serializer = [RKObjectSerializer serializerWithObject:object mapping:mapping]; + NSError *error = nil; id serialization = [serializer serializationForMIMEType:@"application/x-www-form-urlencoded" error:&error]; - NSString* data = [[[NSString alloc] initWithData:[serialization HTTPBody] encoding:NSUTF8StringEncoding] autorelease]; + NSString *data = [[[NSString alloc] initWithData:[serialization HTTPBody] encoding:NSUTF8StringEncoding] autorelease]; data = [data stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; assertThat(error, is(nilValue())); assertThat(data, is(equalTo(@"stuff[key2-form-name]=value2&stuff[key1-form-name]=value1"))); } -- (void)testShouldSerializeToManyRelationships { - RKMappableObject* object = [[RKMappableObject new] autorelease]; +- (void)testShouldSerializeToManyRelationships +{ + RKMappableObject *object = [[RKMappableObject new] autorelease]; object.stringTest = @"The string"; - RKMappableAssociation* association = [[RKMappableAssociation new] autorelease]; + RKMappableAssociation *association = [[RKMappableAssociation new] autorelease]; association.date = [NSDate dateWithTimeIntervalSince1970:0]; object.hasMany = [NSSet setWithObject:association]; // Setup object mappings - RKObjectMapping* objectMapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; + RKObjectMapping *objectMapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; [objectMapping mapAttributes:@"stringTest", nil]; - RKObjectMapping* relationshipMapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; + RKObjectMapping *relationshipMapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; [relationshipMapping mapAttributes:@"date", nil]; [objectMapping mapRelationship:@"hasMany" withMapping:relationshipMapping]; // Serialize - RKObjectSerializer* serializer = [RKObjectSerializer serializerWithObject:object mapping:objectMapping]; - NSError* error = nil; + RKObjectSerializer *serializer = [RKObjectSerializer serializerWithObject:object mapping:objectMapping]; + NSError *error = nil; id serialization = [serializer serializationForMIMEType:@"application/json" error:&error]; assertThat(error, is(nilValue())); - NSString* data = [[[NSString alloc] initWithData:[serialization HTTPBody] encoding:NSUTF8StringEncoding] autorelease]; + NSString *data = [[[NSString alloc] initWithData:[serialization HTTPBody] encoding:NSUTF8StringEncoding] autorelease]; data = [data stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; assertThat(data, is(equalTo(@"{\"hasMany\":[{\"date\":\"1970-01-01 00:00:00 +0000\"}],\"stringTest\":\"The string\"}"))); } -- (void)testShouldSerializeAnNSNumberContainingABooleanToTrueFalseIfRequested { - NSDictionary* object = [NSDictionary dictionaryWithObjectsAndKeys:@"value1", @"key1", [NSNumber numberWithBool:YES], @"boolean", nil]; - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[NSDictionary class]]; - RKObjectAttributeMapping* attributeMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"boolean" toKeyPath:@"boolean-value"]; +- (void)testShouldSerializeAnNSNumberContainingABooleanToTrueFalseIfRequested +{ + NSDictionary *object = [NSDictionary dictionaryWithObjectsAndKeys:@"value1", @"key1", [NSNumber numberWithBool:YES], @"boolean", nil]; + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSDictionary class]]; + RKObjectAttributeMapping *attributeMapping = [RKObjectAttributeMapping mappingFromKeyPath:@"boolean" toKeyPath:@"boolean-value"]; [mapping addAttributeMapping:attributeMapping]; - RKObjectSerializer* serializer = [RKObjectSerializer serializerWithObject:object mapping:mapping]; + RKObjectSerializer *serializer = [RKObjectSerializer serializerWithObject:object mapping:mapping]; - NSError* error = nil; + NSError *error = nil; id serialization = [serializer serializationForMIMEType:@"application/json" error:&error]; - NSString* data = [[[NSString alloc] initWithData:[serialization HTTPBody] encoding:NSUTF8StringEncoding] autorelease]; + NSString *data = [[[NSString alloc] initWithData:[serialization HTTPBody] encoding:NSUTF8StringEncoding] autorelease]; data = [data stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; assertThat(error, is(nilValue())); assertThat(data, is(equalTo(@"{\"boolean-value\":true}"))); } -- (void)testShouldSerializeANSOrderedSetToJSON { - NSDictionary* object = [NSDictionary dictionaryWithObjectsAndKeys:@"value1", @"key1", +- (void)testShouldSerializeANSOrderedSetToJSON +{ + NSDictionary *object = [NSDictionary dictionaryWithObjectsAndKeys:@"value1", @"key1", [NSOrderedSet orderedSetWithObjects:@"setElementOne", @"setElementTwo", @"setElementThree", nil], @"set", nil]; - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[NSDictionary class]]; + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[NSDictionary class]]; [mapping addAttributeMapping:[RKObjectAttributeMapping mappingFromKeyPath:@"key1" toKeyPath:@"key1-form-name"]]; [mapping addAttributeMapping:[RKObjectAttributeMapping mappingFromKeyPath:@"set" toKeyPath:@"set-form-name"]]; - RKObjectSerializer* serializer = [RKObjectSerializer serializerWithObject:object mapping:mapping]; + RKObjectSerializer *serializer = [RKObjectSerializer serializerWithObject:object mapping:mapping]; - NSError* error = nil; + NSError *error = nil; id serialization = [serializer serializationForMIMEType:@"application/json" error:&error]; - NSString* data = [[[NSString alloc] initWithData:[serialization HTTPBody] encoding:NSUTF8StringEncoding] autorelease]; + NSString *data = [[[NSString alloc] initWithData:[serialization HTTPBody] encoding:NSUTF8StringEncoding] autorelease]; data = [data stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; assertThat(error, is(nilValue())); diff --git a/Tests/Logic/ObjectMapping/RKParserRegistryTest.m b/Tests/Logic/ObjectMapping/RKParserRegistryTest.m index 0304510c93..b8d9893ffe 100644 --- a/Tests/Logic/ObjectMapping/RKParserRegistryTest.m +++ b/Tests/Logic/ObjectMapping/RKParserRegistryTest.m @@ -30,22 +30,25 @@ @interface RKParserRegistryTest : RKTestCase { @implementation RKParserRegistryTest -- (void)testShouldEnableRegistrationFromMIMETypeToParserClasses { - RKParserRegistry* registry = [[RKParserRegistry new] autorelease]; +- (void)testShouldEnableRegistrationFromMIMETypeToParserClasses +{ + RKParserRegistry *registry = [[RKParserRegistry new] autorelease]; [registry setParserClass:[RKJSONParserJSONKit class] forMIMEType:RKMIMETypeJSON]; Class parserClass = [registry parserClassForMIMEType:RKMIMETypeJSON]; assertThat(NSStringFromClass(parserClass), is(equalTo(@"RKJSONParserJSONKit"))); } -- (void)testShouldInstantiateParserObjects { - RKParserRegistry* registry = [[RKParserRegistry new] autorelease]; +- (void)testShouldInstantiateParserObjects +{ + RKParserRegistry *registry = [[RKParserRegistry new] autorelease]; [registry setParserClass:[RKJSONParserJSONKit class] forMIMEType:RKMIMETypeJSON]; id parser = [registry parserForMIMEType:RKMIMETypeJSON]; assertThat(parser, is(instanceOf([RKJSONParserJSONKit class]))); } -- (void)testShouldAutoconfigureBasedOnReflection { - RKParserRegistry* registry = [[RKParserRegistry new] autorelease]; +- (void)testShouldAutoconfigureBasedOnReflection +{ + RKParserRegistry *registry = [[RKParserRegistry new] autorelease]; [registry autoconfigure]; id parser = [registry parserForMIMEType:RKMIMETypeJSON]; assertThat(parser, is(instanceOf([RKJSONParserJSONKit class]))); @@ -53,14 +56,16 @@ - (void)testShouldAutoconfigureBasedOnReflection { assertThat(parser, is(instanceOf([RKXMLParserXMLReader class]))); } -- (void)testRetrievalOfExactStringMatchForMIMEType { - RKParserRegistry* registry = [[RKParserRegistry new] autorelease]; +- (void)testRetrievalOfExactStringMatchForMIMEType +{ + RKParserRegistry *registry = [[RKParserRegistry new] autorelease]; [registry setParserClass:[RKJSONParserJSONKit class] forMIMEType:RKMIMETypeJSON]; id parser = [registry parserForMIMEType:RKMIMETypeJSON]; assertThat(parser, is(instanceOf([RKJSONParserJSONKit class]))); } -- (void)testRetrievalOfRegularExpressionMatchForMIMEType { +- (void)testRetrievalOfRegularExpressionMatchForMIMEType +{ RKParserRegistry *registry = [[RKParserRegistry new] autorelease]; NSError *error = nil; NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"application/xml\\+\\w+" options:0 error:&error]; @@ -69,7 +74,8 @@ - (void)testRetrievalOfRegularExpressionMatchForMIMEType { assertThat(parser, is(instanceOf([RKJSONParserJSONKit class]))); } -- (void)testRetrievalOfExactStringMatchIsFavoredOverRegularExpression { +- (void)testRetrievalOfExactStringMatchIsFavoredOverRegularExpression +{ RKParserRegistry *registry = [[RKParserRegistry new] autorelease]; NSError *error = nil; NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"application/xml\\+\\w+" options:0 error:&error]; diff --git a/Tests/Logic/Support/NSDictionary+RKRequestSerializationTest.m b/Tests/Logic/Support/NSDictionary+RKRequestSerializationTest.m index e0392e2d5a..2a6a5402e2 100644 --- a/Tests/Logic/Support/NSDictionary+RKRequestSerializationTest.m +++ b/Tests/Logic/Support/NSDictionary+RKRequestSerializationTest.m @@ -29,52 +29,59 @@ @interface NSDictionary_RKRequestSerializationTest : RKTestCase { @implementation NSDictionary_RKRequestSerializationTest -- (void)testShouldHaveKeysAndValuesDictionaryInitializer { - NSDictionary* dictionary1 = [NSDictionary dictionaryWithObjectsAndKeys:@"value", @"key", @"value2", @"key2", nil]; - NSDictionary* dictionary2 = [NSDictionary dictionaryWithKeysAndObjects:@"key", @"value", @"key2", @"value2", nil]; +- (void)testShouldHaveKeysAndValuesDictionaryInitializer +{ + NSDictionary *dictionary1 = [NSDictionary dictionaryWithObjectsAndKeys:@"value", @"key", @"value2", @"key2", nil]; + NSDictionary *dictionary2 = [NSDictionary dictionaryWithKeysAndObjects:@"key", @"value", @"key2", @"value2", nil]; assertThat(dictionary2, is(equalTo(dictionary1))); } -- (void)testShouldEncodeUnicodeStrings { +- (void)testShouldEncodeUnicodeStrings +{ NSString *unicode = [NSString stringWithFormat:@"%CNo ser ni%Co, ser b%Cfalo%C%C", 0x00A1, 0x00F1, 0x00FA, 0x2026, 0x0021]; NSDictionary *dictionary = [NSDictionary dictionaryWithObject:unicode forKey:@"utf8"]; NSString *validUnicode = @"utf8=%C2%A1No%20ser%20ni%C3%B1o%2C%20ser%20b%C3%BAfalo%E2%80%A6%21"; assertThat([dictionary stringWithURLEncodedEntries], is(equalTo(validUnicode))); } -- (void)testShouldEncodeURLStrings { +- (void)testShouldEncodeURLStrings +{ NSString *url = @"http://some.server.com/path/action?subject=\"That thing I sent\"&email=\"me@me.com\""; NSDictionary *dictionary = [NSDictionary dictionaryWithObject:url forKey:@"url"]; NSString *validURL = @"url=http%3A%2F%2Fsome.server.com%2Fpath%2Faction%3Fsubject%3D%22That%20thing%20I%20sent%22%26email%3D%22me%40me.com%22"; assertThat([dictionary stringWithURLEncodedEntries], is(equalTo(validURL))); } -- (void)testShouldEncodeArrays { +- (void)testShouldEncodeArrays +{ NSArray *array = [NSArray arrayWithObjects:@"item1", @"item2", nil]; NSDictionary *dictionary = [NSDictionary dictionaryWithObject:array forKey:@"anArray"]; NSString *validArray = @"anArray[]=item1&anArray[]=item2"; assertThat([dictionary stringWithURLEncodedEntries], is(equalTo(validArray))); } -- (void)testShouldEncodeDictionaries { +- (void)testShouldEncodeDictionaries +{ NSDictionary *subDictionary = [NSDictionary dictionaryWithObject:@"value1" forKey:@"key1"]; NSDictionary *dictionary = [NSDictionary dictionaryWithObject:subDictionary forKey:@"aDictionary"]; NSString *validDictionary = @"aDictionary[key1]=value1"; assertThat([dictionary stringWithURLEncodedEntries], is(equalTo(validDictionary))); } -- (void)testShouldEncodeArrayOfDictionaries { - NSDictionary * dictA = [NSDictionary dictionaryWithKeysAndObjects:@"a",@"x",@"b",@"y", nil]; - NSDictionary * dictB = [NSDictionary dictionaryWithKeysAndObjects:@"a",@"1",@"b",@"2", nil]; +- (void)testShouldEncodeArrayOfDictionaries +{ + NSDictionary *dictA = [NSDictionary dictionaryWithKeysAndObjects:@"a", @"x", @"b", @"y", nil]; + NSDictionary *dictB = [NSDictionary dictionaryWithKeysAndObjects:@"a", @"1", @"b", @"2", nil]; - NSArray * array = [NSArray arrayWithObjects: dictA, dictB, nil]; - NSDictionary * dictRoot = [NSDictionary dictionaryWithKeysAndObjects:@"root", array, nil]; + NSArray *array = [NSArray arrayWithObjects:dictA, dictB, nil]; + NSDictionary *dictRoot = [NSDictionary dictionaryWithKeysAndObjects:@"root", array, nil]; - NSString * validString = @"root[][a]=x&root[][b]=y&root[][a]=1&root[][b]=2"; + NSString *validString = @"root[][a]=x&root[][b]=y&root[][a]=1&root[][b]=2"; assertThat([dictRoot stringWithURLEncodedEntries], is(equalTo(validString))); } -- (void)testShouldEncodeRecursiveArrays { +- (void)testShouldEncodeRecursiveArrays +{ NSArray *recursiveArray3 = [NSArray arrayWithObjects:@"item1", @"item2", nil]; NSArray *recursiveArray2 = [NSArray arrayWithObject:recursiveArray3]; NSArray *recursiveArray1 = [NSArray arrayWithObject:recursiveArray2]; diff --git a/Tests/Logic/Support/NSStringRestKitTest.m b/Tests/Logic/Support/NSStringRestKitTest.m index c9ddcf2d9b..73112c8e0f 100755 --- a/Tests/Logic/Support/NSStringRestKitTest.m +++ b/Tests/Logic/Support/NSStringRestKitTest.m @@ -28,11 +28,12 @@ @interface NSStringRestKitTest : RKTestCase @implementation NSStringRestKitTest -- (void)testShouldAppendQueryParameters { +- (void)testShouldAppendQueryParameters +{ NSString *resourcePath = @"/controller/objects/"; NSDictionary *queryParams = [NSDictionary dictionaryWithObjectsAndKeys: @"ascend", @"sortOrder", - @"name", @"groupBy",nil]; + @"name", @"groupBy", nil]; NSString *resultingPath = [resourcePath stringByAppendingQueryParameters:queryParams]; assertThat(resultingPath, isNot(equalTo(nil))); NSString *expectedPath1 = @"/controller/objects/?sortOrder=ascend&groupBy=name"; @@ -42,7 +43,8 @@ - (void)testShouldAppendQueryParameters { assertThatBool(isValidPath, is(equalToBool(YES))); } -- (void)testShouldInterpolateObjects { +- (void)testShouldInterpolateObjects +{ RKObjectMapperTestModel *person = [[[RKObjectMapperTestModel alloc] init] autorelease]; person.name = @"CuddleGuts"; person.age = [NSNumber numberWithInt:6]; @@ -52,7 +54,8 @@ - (void)testShouldInterpolateObjects { assertThat(interpolatedPath, is(equalTo(expectedPath))); } -- (void)testShouldInterpolateObjectsWithDeprecatedParentheses { +- (void)testShouldInterpolateObjectsWithDeprecatedParentheses +{ RKObjectMapperTestModel *person = [[[RKObjectMapperTestModel alloc] init] autorelease]; person.name = @"CuddleGuts"; person.age = [NSNumber numberWithInt:6]; @@ -62,7 +65,8 @@ - (void)testShouldInterpolateObjectsWithDeprecatedParentheses { assertThat(interpolatedPath, is(equalTo(expectedPath))); } -- (void)testShouldParseQueryParameters { +- (void)testShouldParseQueryParameters +{ NSString *resourcePath = @"/views/thing/?keyA=valA&keyB=valB"; NSDictionary *queryParams = [resourcePath queryParametersUsingEncoding:NSASCIIStringEncoding]; assertThat(queryParams, isNot(empty())); @@ -70,17 +74,20 @@ - (void)testShouldParseQueryParameters { assertThat(queryParams, hasEntries(@"keyA", @"valA", @"keyB", @"valB", nil)); } -- (void)testReturningTheMIMETypeForAPathWithXMLExtension { +- (void)testReturningTheMIMETypeForAPathWithXMLExtension +{ NSString *MIMEType = [@"/path/to/file.xml" MIMETypeForPathExtension]; assertThat(MIMEType, is(equalTo(@"application/xml"))); } -- (void)testReturningTheMIMETypeForAPathWithJSONExtension { +- (void)testReturningTheMIMETypeForAPathWithJSONExtension +{ NSString *MIMEType = [@"/path/to/file.json" MIMETypeForPathExtension]; assertThat(MIMEType, is(equalTo(@"application/json"))); } -- (void)testShouldKnowIfTheReceiverContainsAnIPAddress { +- (void)testShouldKnowIfTheReceiverContainsAnIPAddress +{ assertThatBool([@"127.0.0.1" isIPAddress], equalToBool(YES)); assertThatBool([@"173.45.234.197" isIPAddress], equalToBool(YES)); assertThatBool([@"google.com" isIPAddress], equalToBool(NO)); diff --git a/Tests/Logic/Support/RKDotNetDateFormatterTest.m b/Tests/Logic/Support/RKDotNetDateFormatterTest.m index de14dbf9a2..67baa13315 100644 --- a/Tests/Logic/Support/RKDotNetDateFormatterTest.m +++ b/Tests/Logic/Support/RKDotNetDateFormatterTest.m @@ -15,7 +15,8 @@ @interface RKDotNetDateFormatterTest : RKTestCase @implementation RKDotNetDateFormatterTest -- (void)testShouldInstantiateAFormatterWithDefaultGMTTimeZone { +- (void)testShouldInstantiateAFormatterWithDefaultGMTTimeZone +{ RKDotNetDateFormatter *formatter = [RKDotNetDateFormatter dotNetDateFormatter]; NSTimeZone *timeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"]; assertThat(formatter, isNot(equalTo(nil))); @@ -23,35 +24,40 @@ - (void)testShouldInstantiateAFormatterWithDefaultGMTTimeZone { } -- (void)testShouldInstantiateAFormatterWithATimeZone { +- (void)testShouldInstantiateAFormatterWithATimeZone +{ NSTimeZone *timeZoneCST = [NSTimeZone timeZoneWithAbbreviation:@"CST"]; RKDotNetDateFormatter *formatter = [RKDotNetDateFormatter dotNetDateFormatterWithTimeZone:timeZoneCST]; assertThat(formatter, isNot(equalTo(nil))); assertThat(formatter.timeZone, is(equalTo(timeZoneCST))); } -- (void)testShouldCreateADateFromDotNetThatWithAnOffset { +- (void)testShouldCreateADateFromDotNetThatWithAnOffset +{ NSString *dotNetString = @"/Date(1000212360000-0400)/"; RKDotNetDateFormatter *formatter = [RKDotNetDateFormatter dotNetDateFormatter]; NSDate *date = [formatter dateFromString:dotNetString]; assertThat([date description], is(equalTo(@"2001-09-11 12:46:00 +0000"))); } -- (void)testShouldCreateADateFromDotNetWithoutAnOffset { +- (void)testShouldCreateADateFromDotNetWithoutAnOffset +{ NSString *dotNetString = @"/Date(1112715000000)/"; RKDotNetDateFormatter *formatter = [RKDotNetDateFormatter dotNetDateFormatter]; NSDate *date = [formatter dateFromString:dotNetString]; assertThat([date description], is(equalTo(@"2005-04-05 15:30:00 +0000"))); } -- (void)testShouldCreateADateFromDotNetBefore1970WithoutAnOffset { +- (void)testShouldCreateADateFromDotNetBefore1970WithoutAnOffset +{ NSString *dotNetString = @"/Date(-864000000000)/"; RKDotNetDateFormatter *formatter = [RKDotNetDateFormatter dotNetDateFormatter]; NSDate *date = [formatter dateFromString:dotNetString]; assertThat([date description], is(equalTo(@"1942-08-16 00:00:00 +0000"))); } -- (void)testShouldFailToCreateADateFromInvalidStrings { +- (void)testShouldFailToCreateADateFromInvalidStrings +{ RKDotNetDateFormatter *formatter = [RKDotNetDateFormatter dotNetDateFormatter]; NSDate *date = [formatter dateFromString:nil]; assertThat(date, is(equalTo(nil))); @@ -61,7 +67,8 @@ - (void)testShouldFailToCreateADateFromInvalidStrings { assertThat(date, is(equalTo(nil))); } -- (void)testShouldCreateADotNetStringFromADateWithATimeZone { +- (void)testShouldCreateADotNetStringFromADateWithATimeZone +{ NSTimeZone *timeZoneEST = [NSTimeZone timeZoneWithAbbreviation:@"EST"]; RKDotNetDateFormatter *formatter = [RKDotNetDateFormatter dotNetDateFormatterWithTimeZone:timeZoneEST]; NSDate *referenceDate = [NSDate dateWithTimeIntervalSince1970:1000212360]; @@ -70,14 +77,16 @@ - (void)testShouldCreateADotNetStringFromADateWithATimeZone { assertThat(string, is(equalTo(@"/Date(1000212360000-0400)/"))); } -- (void)testShouldCreateADotNetStringFromADateBefore1970WithoutAnOffset { +- (void)testShouldCreateADotNetStringFromADateBefore1970WithoutAnOffset +{ RKDotNetDateFormatter *formatter = [RKDotNetDateFormatter dotNetDateFormatter]; NSDate *referenceDate = [NSDate dateWithTimeIntervalSince1970:-1000212360]; NSString *string = [formatter stringFromDate:referenceDate]; assertThat(string, is(equalTo(@"/Date(-1000212360000+0000)/"))); } -- (void)testShouldCreateADateWithGetObjectValueForString { +- (void)testShouldCreateADateWithGetObjectValueForString +{ RKDotNetDateFormatter *formatter = [RKDotNetDateFormatter dotNetDateFormatter]; NSString *dotNetString = @"/Date(1000212360000-0400)/"; diff --git a/Tests/Logic/Support/RKJSONParserJSONKitTest.m b/Tests/Logic/Support/RKJSONParserJSONKitTest.m index 4a5637e745..94245375d9 100644 --- a/Tests/Logic/Support/RKJSONParserJSONKitTest.m +++ b/Tests/Logic/Support/RKJSONParserJSONKitTest.m @@ -27,9 +27,10 @@ @interface RKJSONParserJSONKitTest : RKTestCase @implementation RKJSONParserJSONKitTest -- (void)testShouldParseEmptyResults { - NSError* error = nil; - RKJSONParserJSONKit* parser = [[RKJSONParserJSONKit new] autorelease]; +- (void)testShouldParseEmptyResults +{ + NSError *error = nil; + RKJSONParserJSONKit *parser = [[RKJSONParserJSONKit new] autorelease]; id parsingResult = [parser objectFromString:nil error:&error]; assertThat(parsingResult, is(equalTo(nil))); assertThat(error, is(equalTo(nil))); diff --git a/Tests/Logic/Support/RKMutableBlockDictionaryTest.m b/Tests/Logic/Support/RKMutableBlockDictionaryTest.m index 544ffbaef9..3ba9d9e5ca 100644 --- a/Tests/Logic/Support/RKMutableBlockDictionaryTest.m +++ b/Tests/Logic/Support/RKMutableBlockDictionaryTest.m @@ -15,22 +15,25 @@ @interface RKMutableBlockDictionaryTest : RKTestCase @implementation RKMutableBlockDictionaryTest -- (void)testLetYouAssignABlockToTheDictionary { - RKMutableBlockDictionary* blockDictionary = [[RKMutableBlockDictionary new] autorelease]; +- (void)testLetYouAssignABlockToTheDictionary +{ + RKMutableBlockDictionary *blockDictionary = [[RKMutableBlockDictionary new] autorelease]; [blockDictionary setValueWithBlock:^id{ return @"Value from the block!"; } forKey:@"theKey"]; assertThat([blockDictionary valueForKey:@"theKey"], is(equalTo(@"Value from the block!"))); } -- (void)testLetYouUseKVC { - RKMutableBlockDictionary* blockDictionary = [[RKMutableBlockDictionary new] autorelease]; +- (void)testLetYouUseKVC +{ + RKMutableBlockDictionary *blockDictionary = [[RKMutableBlockDictionary new] autorelease]; [blockDictionary setValue:@"a value" forKey:@"a key"]; assertThat([blockDictionary valueForKey:@"a key"], is(equalTo(@"a value"))); } -- (void)testLetYouAccessABlockValueUsingAKeyPath { - RKMutableBlockDictionary* blockDictionary = [[RKMutableBlockDictionary new] autorelease]; +- (void)testLetYouAccessABlockValueUsingAKeyPath +{ + RKMutableBlockDictionary *blockDictionary = [[RKMutableBlockDictionary new] autorelease]; [blockDictionary setValueWithBlock:^id{ return @"Value from the block!"; } forKey:@"theKey"]; - NSDictionary* otherDictionary = [NSDictionary dictionaryWithObject:blockDictionary forKey:@"dictionary"]; + NSDictionary *otherDictionary = [NSDictionary dictionaryWithObject:blockDictionary forKey:@"dictionary"]; assertThat([otherDictionary valueForKeyPath:@"dictionary.theKey"], is(equalTo(@"Value from the block!"))); } diff --git a/Tests/Logic/Support/RKPathMatcherTest.m b/Tests/Logic/Support/RKPathMatcherTest.m index c4124effb8..f572906eaf 100755 --- a/Tests/Logic/Support/RKPathMatcherTest.m +++ b/Tests/Logic/Support/RKPathMatcherTest.m @@ -27,7 +27,8 @@ @interface RKPathMatcherTest : RKTestCase @implementation RKPathMatcherTest -- (void)testShouldMatchPathsWithQueryArguments { +- (void)testShouldMatchPathsWithQueryArguments +{ NSDictionary *arguments = nil; RKPathMatcher *pathMatcher = [RKPathMatcher matcherWithPath:@"/this/is/my/backend?foo=bar&this=that"]; BOOL isMatchingPattern = [pathMatcher matchesPattern:@"/this/is/:controllerName/:entityName" tokenizeQueryStrings:YES parsedArguments:&arguments]; @@ -37,7 +38,8 @@ - (void)testShouldMatchPathsWithQueryArguments { } -- (void)testShouldMatchPathsWithEscapedArguments { +- (void)testShouldMatchPathsWithEscapedArguments +{ NSDictionary *arguments = nil; RKPathMatcher *pathMatcher = [RKPathMatcher matcherWithPath:@"/bills/tx/82/SB%2014?apikey=GC12d0c6af"]; BOOL isMatchingPattern = [pathMatcher matchesPattern:@"/bills/:stateID/:session/:billID" tokenizeQueryStrings:YES parsedArguments:&arguments]; @@ -47,24 +49,27 @@ - (void)testShouldMatchPathsWithEscapedArguments { } -- (void)testShouldMatchPathsWithoutQueryArguments { +- (void)testShouldMatchPathsWithoutQueryArguments +{ NSDictionary *arguments = nil; - RKPathMatcher* patternMatcher = [RKPathMatcher matcherWithPattern:@"github.com/:username"]; + RKPathMatcher *patternMatcher = [RKPathMatcher matcherWithPattern:@"github.com/:username"]; BOOL isMatchingPattern = [patternMatcher matchesPath:@"github.com/jverkoey" tokenizeQueryStrings:NO parsedArguments:&arguments]; assertThatBool(isMatchingPattern, is(equalToBool(YES))); assertThat(arguments, isNot(empty())); assertThat(arguments, hasEntry(@"username", @"jverkoey")); } -- (void)testShouldMatchPathsWithoutAnyArguments { +- (void)testShouldMatchPathsWithoutAnyArguments +{ NSDictionary *arguments = nil; - RKPathMatcher* patternMatcher = [RKPathMatcher matcherWithPattern:@"/metadata"]; + RKPathMatcher *patternMatcher = [RKPathMatcher matcherWithPattern:@"/metadata"]; BOOL isMatchingPattern = [patternMatcher matchesPath:@"/metadata" tokenizeQueryStrings:NO parsedArguments:&arguments]; assertThatBool(isMatchingPattern, is(equalToBool(YES))); assertThat(arguments, is(empty())); } -- (void)testShouldPerformTwoMatchesInARow { +- (void)testShouldPerformTwoMatchesInARow +{ NSDictionary *arguments = nil; RKPathMatcher *pathMatcher = [RKPathMatcher matcherWithPath:@"/metadata?apikey=GC12d0c6af"]; BOOL isMatchingPattern1 = [pathMatcher matchesPattern:@"/metadata/:stateID" tokenizeQueryStrings:YES parsedArguments:&arguments]; @@ -75,14 +80,16 @@ - (void)testShouldPerformTwoMatchesInARow { assertThat(arguments, hasEntry(@"apikey", @"GC12d0c6af")); } -- (void)testShouldMatchPathsWithDeprecatedParentheses { +- (void)testShouldMatchPathsWithDeprecatedParentheses +{ NSDictionary *arguments = nil; - RKPathMatcher* patternMatcher = [RKPathMatcher matcherWithPattern:@"github.com/(username)"]; + RKPathMatcher *patternMatcher = [RKPathMatcher matcherWithPattern:@"github.com/(username)"]; BOOL isMatchingPattern = [patternMatcher matchesPath:@"github.com/jverkoey" tokenizeQueryStrings:NO parsedArguments:&arguments]; assertThatBool(isMatchingPattern, is(equalToBool(YES))); } -- (void)testShouldCreatePathsFromInterpolatedObjects { +- (void)testShouldCreatePathsFromInterpolatedObjects +{ NSDictionary *person = [NSDictionary dictionaryWithObjectsAndKeys: @"CuddleGuts", @"name", [NSNumber numberWithInt:6], @"age", nil]; RKPathMatcher *matcher = [RKPathMatcher matcherWithPattern:@"/people/:name/:age"]; @@ -92,7 +99,8 @@ - (void)testShouldCreatePathsFromInterpolatedObjects { assertThat(interpolatedPath, is(equalTo(expectedPath))); } -- (void)testShouldCreatePathsFromInterpolatedObjectsWithDeprecatedParentheses { +- (void)testShouldCreatePathsFromInterpolatedObjectsWithDeprecatedParentheses +{ NSDictionary *person = [NSDictionary dictionaryWithObjectsAndKeys: @"CuddleGuts", @"name", [NSNumber numberWithInt:6], @"age", nil]; RKPathMatcher *matcher = [RKPathMatcher matcherWithPattern:@"/people/(name)/(age)"]; @@ -102,7 +110,8 @@ - (void)testShouldCreatePathsFromInterpolatedObjectsWithDeprecatedParentheses { assertThat(interpolatedPath, is(equalTo(expectedPath))); } -- (void)testShouldCreatePathsFromInterpolatedObjectsWithAddedEscapes { +- (void)testShouldCreatePathsFromInterpolatedObjectsWithAddedEscapes +{ NSDictionary *person = [NSDictionary dictionaryWithObjectsAndKeys: @"JUICE|BOX&121", @"password", @"Joe Bob Briggs", @"name", [NSNumber numberWithInt:15], @"group", nil]; RKPathMatcher *matcher = [RKPathMatcher matcherWithPattern:@"/people/:group/:name?password=:password"]; @@ -112,7 +121,8 @@ - (void)testShouldCreatePathsFromInterpolatedObjectsWithAddedEscapes { assertThat(interpolatedPath, is(equalTo(expectedPath))); } -- (void)testShouldCreatePathsFromInterpolatedObjectsWithoutAddedEscapes { +- (void)testShouldCreatePathsFromInterpolatedObjectsWithoutAddedEscapes +{ NSDictionary *person = [NSDictionary dictionaryWithObjectsAndKeys: @"JUICE|BOX&121", @"password", @"Joe Bob Briggs", @"name", [NSNumber numberWithInt:15], @"group", nil]; RKPathMatcher *matcher = [RKPathMatcher matcherWithPattern:@"/people/:group/:name?password=:password"]; @@ -122,7 +132,8 @@ - (void)testShouldCreatePathsFromInterpolatedObjectsWithoutAddedEscapes { assertThat(interpolatedPath, is(equalTo(expectedPath))); } -- (void)testShouldCreatePathsThatIncludePatternArgumentsFollowedByEscapedNonPatternDots { +- (void)testShouldCreatePathsThatIncludePatternArgumentsFollowedByEscapedNonPatternDots +{ NSDictionary *arguments = [NSDictionary dictionaryWithObjectsAndKeys:@"Resources", @"filename", nil]; RKPathMatcher *matcher = [RKPathMatcher matcherWithPattern:@"/directory/:filename\\.json"]; NSString *interpolatedPath = [matcher pathFromObject:arguments]; diff --git a/Tests/Logic/Support/RKXMLParserTest.m b/Tests/Logic/Support/RKXMLParserTest.m index d7a5b5e1ee..85b4c97e1b 100644 --- a/Tests/Logic/Support/RKXMLParserTest.m +++ b/Tests/Logic/Support/RKXMLParserTest.m @@ -23,12 +23,12 @@ // See Tests/Fixtures/XML/tab_data.xml @interface RKTestTabData : NSObject { - NSString* _title; - NSString* _summary; + NSString *_title; + NSString *_summary; } -@property (nonatomic, retain) NSString* title; -@property (nonatomic, retain) NSString* summary; +@property (nonatomic, retain) NSString *title; +@property (nonatomic, retain) NSString *summary; @end @@ -47,10 +47,11 @@ @interface RKXMLParserTest : RKTestCase { @implementation RKXMLParserTest -- (void)testShouldMapASingleXMLObjectPayloadToADictionary { - NSString* data = @"\n\n 2.4\n string\n 1\n\n"; +- (void)testShouldMapASingleXMLObjectPayloadToADictionary +{ + NSString *data = @"\n\n 2.4\n string\n 1\n\n"; NSError *error = [[NSError alloc] init]; - RKXMLParserXMLReader* parser = [[RKXMLParserXMLReader new] autorelease]; + RKXMLParserXMLReader *parser = [[RKXMLParserXMLReader new] autorelease]; id result = [parser objectFromString:data error:&error]; assertThat(NSStringFromClass([result class]), is(equalTo(@"__NSCFDictionary"))); assertThatFloat([[[result valueForKeyPath:@"hash.float"] valueForKey:@"text"] floatValue], is(equalToFloat(2.4f))); @@ -58,12 +59,13 @@ - (void)testShouldMapASingleXMLObjectPayloadToADictionary { assertThat([result valueForKeyPath:@"hash.string"], is(equalTo(@"string"))); } -- (void)testShouldMapMultipleObjectsToAnArray { - NSString* data = @"\n\n \n 2.4\n string\n 1\n \n \n 1\n \n\n"; +- (void)testShouldMapMultipleObjectsToAnArray +{ + NSString *data = @"\n\n \n 2.4\n string\n 1\n \n \n 1\n \n\n"; NSError *error = [[NSError alloc] init]; - RKXMLParserXMLReader* parser = [[RKXMLParserXMLReader new] autorelease]; + RKXMLParserXMLReader *parser = [[RKXMLParserXMLReader new] autorelease]; id result = [parser objectFromString:data error:&error]; - NSArray* records = (NSArray*)[result valueForKeyPath:@"records.record"]; + NSArray *records = (NSArray *)[result valueForKeyPath:@"records.record"]; assertThatUnsignedInteger([records count], is(equalToInt(2))); id result1 = [records objectAtIndex:0]; assertThat(NSStringFromClass([result1 class]), is(equalTo(@"__NSCFDictionary"))); @@ -71,76 +73,80 @@ - (void)testShouldMapMultipleObjectsToAnArray { assertThatInt([[[result1 valueForKeyPath:@"number"] valueForKey:@"text"] intValue], is(equalToInt(1))); assertThat([result1 valueForKeyPath:@"string"], is(equalTo(@"string"))); id result2 = [records objectAtIndex:1]; - assertThatInt([[[result2 valueForKeyPath:@"another-number"] valueForKey:@"text"]intValue], is(equalToInt(1))); + assertThatInt([[[result2 valueForKeyPath:@"another-number"] valueForKey:@"text"] intValue], is(equalToInt(1))); } -- (void)testShouldMapXML { - RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[RKTestTabData class]]; +- (void)testShouldMapXML +{ + RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKTestTabData class]]; [mapping mapAttributes:@"title", @"summary", nil]; - RKObjectMappingProvider* provider = [[RKObjectMappingProvider alloc] init]; + RKObjectMappingProvider *provider = [[RKObjectMappingProvider alloc] init]; id data = [RKTestFixture parsedObjectWithContentsOfFixture:@"tab_data.xml"]; assertThat([data valueForKeyPath:@"tabdata.item"], is(instanceOf([NSArray class]))); [provider setMapping:mapping forKeyPath:@"tabdata.item"]; - RKObjectMapper* mapper = [RKObjectMapper mapperWithObject:data mappingProvider:provider]; - RKObjectMappingResult* result = [mapper performMapping]; + RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:data mappingProvider:provider]; + RKObjectMappingResult *result = [mapper performMapping]; assertThatUnsignedInteger([[result asCollection] count], is(equalToInt(2))); assertThatUnsignedInteger([[data valueForKeyPath:@"tabdata.title"] count], is(equalToInt(2))); assertThatUnsignedInteger([[data valueForKeyPath:@"tabdata.item"] count], is(equalToInt(2))); } -- (void)testShouldParseXMLWithAttributes { - NSString* XML = [RKTestFixture stringWithContentsOfFixture:@"container_attributes.xml"]; +- (void)testShouldParseXMLWithAttributes +{ + NSString *XML = [RKTestFixture stringWithContentsOfFixture:@"container_attributes.xml"]; NSError *error = [[NSError alloc] init]; - RKXMLParserXMLReader* parser = [[RKXMLParserXMLReader new] autorelease]; + RKXMLParserXMLReader *parser = [[RKXMLParserXMLReader new] autorelease]; NSDictionary *result = [parser objectFromString:XML error:&error]; assertThat(result, is(instanceOf([NSDictionary class]))); - NSArray* elements = [[result objectForKey:@"elements"] objectForKey:@"element"]; + NSArray *elements = [[result objectForKey:@"elements"] objectForKey:@"element"]; assertThat(elements, isNot(nilValue())); assertThat(elements, is(instanceOf([NSArray class]))); assertThat(elements, hasCountOf(2)); - NSDictionary* firstElement = [elements objectAtIndex:0]; + NSDictionary *firstElement = [elements objectAtIndex:0]; assertThat([firstElement objectForKey:@"attribute"], is(equalTo(@"1"))); assertThat([firstElement objectForKey:@"subelement"], is(equalTo(@"text"))); - NSDictionary* secondElement = [elements objectAtIndex:1]; + NSDictionary *secondElement = [elements objectAtIndex:1]; assertThat([secondElement objectForKey:@"attribute"], is(equalTo(@"2"))); assertThat([secondElement objectForKey:@"subelement"], is(equalTo(@"text2"))); } -- (void)testShouldParseXMLWithAttributesInTextNodes { - NSString* XML = [RKTestFixture stringWithContentsOfFixture:@"attributes_without_text_content.xml"]; +- (void)testShouldParseXMLWithAttributesInTextNodes +{ + NSString *XML = [RKTestFixture stringWithContentsOfFixture:@"attributes_without_text_content.xml"]; NSError *error = [[NSError alloc] init]; - RKXMLParserXMLReader* parser = [[RKXMLParserXMLReader new] autorelease]; + RKXMLParserXMLReader *parser = [[RKXMLParserXMLReader new] autorelease]; NSDictionary *result = [parser objectFromString:XML error:&error]; - NSDictionary* exchangeRate = [result objectForKey:@"exchange_rate"]; + NSDictionary *exchangeRate = [result objectForKey:@"exchange_rate"]; assertThat(exchangeRate, is(notNilValue())); assertThat([exchangeRate objectForKey:@"type"], is(equalTo(@"XML_RATE_TYPE_EBNK_MIDDLE"))); assertThat([exchangeRate objectForKey:@"valid_from"], is(equalTo(@"2011-08-03 00:00:00.0"))); assertThat([exchangeRate objectForKey:@"name"], nilValue()); // This is to test for bug in parsing - NSArray* currency = [exchangeRate objectForKey:@"currency"]; + NSArray *currency = [exchangeRate objectForKey:@"currency"]; assertThat(currency, hasCountOf(3)); - NSDictionary* firstCurrency = [currency objectAtIndex:0]; + NSDictionary *firstCurrency = [currency objectAtIndex:0]; assertThat(firstCurrency, is(instanceOf([NSDictionary class]))); assertThat([firstCurrency objectForKey:@"name"], is(equalTo(@"AUD"))); assertThat([firstCurrency objectForKey:@"quota"], is(equalTo(@"1"))); assertThat([firstCurrency objectForKey:@"rate"], is(equalTo(@"18.416"))); - NSDictionary* secondCurrency = [currency objectAtIndex:1]; + NSDictionary *secondCurrency = [currency objectAtIndex:1]; assertThat(secondCurrency, is(instanceOf([NSDictionary class]))); assertThat([secondCurrency objectForKey:@"name"], is(equalTo(@"HRK"))); assertThat([secondCurrency objectForKey:@"quota"], is(equalTo(@"1"))); assertThat([secondCurrency objectForKey:@"rate"], is(equalTo(@"3.25017"))); - NSDictionary* thirdCurrency = [currency objectAtIndex:2]; + NSDictionary *thirdCurrency = [currency objectAtIndex:2]; assertThat(thirdCurrency, is(instanceOf([NSDictionary class]))); assertThat([thirdCurrency objectForKey:@"name"], is(equalTo(@"DKK"))); assertThat([thirdCurrency objectForKey:@"quota"], is(equalTo(@"1"))); assertThat([thirdCurrency objectForKey:@"rate"], is(equalTo(@"3.251"))); } -- (void)testShouldNotCrashWhileParsingOrdersXML { +- (void)testShouldNotCrashWhileParsingOrdersXML +{ NSString *XML = [RKTestFixture stringWithContentsOfFixture:@"orders.xml"]; NSError *error = [[NSError alloc] init]; - RKXMLParserXMLReader* parser = [[RKXMLParserXMLReader new] autorelease]; + RKXMLParserXMLReader *parser = [[RKXMLParserXMLReader new] autorelease]; NSException *exception = nil; @try { [parser objectFromString:XML error:&error];; @@ -153,10 +159,11 @@ - (void)testShouldNotCrashWhileParsingOrdersXML { } } -- (void)testShouldParseXMLWithCDATA { +- (void)testShouldParseXMLWithCDATA +{ NSString *XML = [RKTestFixture stringWithContentsOfFixture:@"zend.xml"]; NSError *error = [[NSError alloc] init]; - RKXMLParserXMLReader* parser = [[RKXMLParserXMLReader new] autorelease]; + RKXMLParserXMLReader *parser = [[RKXMLParserXMLReader new] autorelease]; NSDictionary *output = [parser objectFromString:XML error:&error]; NSArray *map = [output valueForKeyPath:@"Api.getList.map"]; assertThat(map, isNot(nilValue())); @@ -166,10 +173,11 @@ - (void)testShouldParseXMLWithCDATA { assertThat([[map objectAtIndex:2] valueForKey:@"subtitle"], is(equalTo(@"Kary lives here."))); } -- (void)testShouldConsiderASingleCloseTagAnEmptyContainer { +- (void)testShouldConsiderASingleCloseTagAnEmptyContainer +{ NSString *XML = @""; NSError *error = [[NSError alloc] init]; - RKXMLParserXMLReader* parser = [[RKXMLParserXMLReader new] autorelease]; + RKXMLParserXMLReader *parser = [[RKXMLParserXMLReader new] autorelease]; NSDictionary *output = [parser objectFromString:XML error:&error]; NSDictionary *users = [output valueForKey:@"users"]; NSLog(@"%@", output); @@ -177,10 +185,11 @@ - (void)testShouldConsiderASingleCloseTagAnEmptyContainer { assertThatBool([users isKindOfClass:[NSDictionary class]], is(equalToBool(YES))); } -- (void)testShouldParseRelativelyComplexXML { +- (void)testShouldParseRelativelyComplexXML +{ NSString *XML = [RKTestFixture stringWithContentsOfFixture:@"national_weather_service.xml"]; NSError *error = [[NSError alloc] init]; - RKXMLParserXMLReader* parser = [[RKXMLParserXMLReader new] autorelease]; + RKXMLParserXMLReader *parser = [[RKXMLParserXMLReader new] autorelease]; NSException *exception = nil; @try { [parser objectFromString:XML error:&error]; @@ -193,11 +202,12 @@ - (void)testShouldParseRelativelyComplexXML { } } -- (void)testShouldParseXMLElementsAndAttributesProperly { +- (void)testShouldParseXMLElementsAndAttributesProperly +{ - NSString* XML = [RKTestFixture stringWithContentsOfFixture:@"channels.xml"]; + NSString *XML = [RKTestFixture stringWithContentsOfFixture:@"channels.xml"]; NSError *error = [[NSError alloc] init]; - RKXMLParserXMLReader* parser = [[RKXMLParserXMLReader new] autorelease]; + RKXMLParserXMLReader *parser = [[RKXMLParserXMLReader new] autorelease]; NSDictionary *result = [parser objectFromString:XML error:&error]; NSLog(@"result : %@", result); diff --git a/Tests/Models/RKCat.h b/Tests/Models/RKCat.h index c8e449556a..214eaf608c 100644 --- a/Tests/Models/RKCat.h +++ b/Tests/Models/RKCat.h @@ -27,17 +27,17 @@ } -@property (nonatomic, retain) NSNumber* age; -@property (nonatomic, retain) NSNumber* birthYear; -@property (nonatomic, retain) NSString* color; -@property (nonatomic, retain) NSDate* createdAt; -@property (nonatomic, retain) NSNumber* humanId; -@property (nonatomic, retain) NSString* name; -@property (nonatomic, retain) NSString* nickName; -@property (nonatomic, retain) NSNumber* railsID; -@property (nonatomic, retain) NSString* sex; -@property (nonatomic, retain) NSDate* updatedAt; - -@property (nonatomic, retain) RKHuman * human; +@property (nonatomic, retain) NSNumber *age; +@property (nonatomic, retain) NSNumber *birthYear; +@property (nonatomic, retain) NSString *color; +@property (nonatomic, retain) NSDate *createdAt; +@property (nonatomic, retain) NSNumber *humanId; +@property (nonatomic, retain) NSString *name; +@property (nonatomic, retain) NSString *nickName; +@property (nonatomic, retain) NSNumber *railsID; +@property (nonatomic, retain) NSString *sex; +@property (nonatomic, retain) NSDate *updatedAt; + +@property (nonatomic, retain) RKHuman *human; @end diff --git a/Tests/Models/RKDynamicMappingModels.h b/Tests/Models/RKDynamicMappingModels.h index 19a2b9fca9..1d18d9159b 100644 --- a/Tests/Models/RKDynamicMappingModels.h +++ b/Tests/Models/RKDynamicMappingModels.h @@ -21,8 +21,8 @@ #import @interface Person : NSObject -@property (nonatomic, retain) NSString* name; -@property (nonatomic, retain) NSArray* friends; +@property (nonatomic, retain) NSString *name; +@property (nonatomic, retain) NSArray *friends; @end @interface Boy : Person diff --git a/Tests/Models/RKEvent.h b/Tests/Models/RKEvent.h index 429b7f4bc9..8f43fded1c 100644 --- a/Tests/Models/RKEvent.h +++ b/Tests/Models/RKEvent.h @@ -25,9 +25,9 @@ } -@property (nonatomic, retain) NSString* eventID; -@property (nonatomic, retain) NSString* eventType; -@property (nonatomic, retain) NSString* location; -@property (nonatomic, retain) NSString* summary; +@property (nonatomic, retain) NSString *eventID; +@property (nonatomic, retain) NSString *eventType; +@property (nonatomic, retain) NSString *location; +@property (nonatomic, retain) NSString *summary; @end diff --git a/Tests/Models/RKHouse.h b/Tests/Models/RKHouse.h index e13a3735fd..7be53903c7 100644 --- a/Tests/Models/RKHouse.h +++ b/Tests/Models/RKHouse.h @@ -25,13 +25,13 @@ } -@property (nonatomic, retain) NSString* city; -@property (nonatomic, retain) NSDate* createdAt; -@property (nonatomic, retain) NSNumber* ownerId; -@property (nonatomic, retain) NSNumber* railsID; -@property (nonatomic, retain) NSString* state; -@property (nonatomic, retain) NSString* street; -@property (nonatomic, retain) NSDate* updatedAt; -@property (nonatomic, retain) NSString* zip; +@property (nonatomic, retain) NSString *city; +@property (nonatomic, retain) NSDate *createdAt; +@property (nonatomic, retain) NSNumber *ownerId; +@property (nonatomic, retain) NSNumber *railsID; +@property (nonatomic, retain) NSString *state; +@property (nonatomic, retain) NSString *street; +@property (nonatomic, retain) NSDate *updatedAt; +@property (nonatomic, retain) NSString *zip; @end diff --git a/Tests/Models/RKHuman.m b/Tests/Models/RKHuman.m index e4d175a8c1..6196e21047 100644 --- a/Tests/Models/RKHuman.m +++ b/Tests/Models/RKHuman.m @@ -39,7 +39,8 @@ @implementation RKHuman @dynamic catIDs; @dynamic catsInOrderByAge; -- (NSString*)polymorphicResourcePath { +- (NSString *)polymorphicResourcePath +{ return @"/this/is/the/path"; } diff --git a/Tests/Models/RKMappableAssociation.h b/Tests/Models/RKMappableAssociation.h index 3a41f09626..56b1fd1fdf 100644 --- a/Tests/Models/RKMappableAssociation.h +++ b/Tests/Models/RKMappableAssociation.h @@ -21,11 +21,11 @@ #import @interface RKMappableAssociation : NSObject { - NSString* _testString; - NSDate* _date; + NSString *_testString; + NSDate *_date; } -@property (nonatomic, retain) NSString* testString; -@property (nonatomic, retain) NSDate* date; +@property (nonatomic, retain) NSString *testString; +@property (nonatomic, retain) NSDate *date; @end diff --git a/Tests/Models/RKMappableAssociation.m b/Tests/Models/RKMappableAssociation.m index 804065922d..f7caa33ea7 100644 --- a/Tests/Models/RKMappableAssociation.m +++ b/Tests/Models/RKMappableAssociation.m @@ -25,7 +25,8 @@ @implementation RKMappableAssociation @synthesize testString = _testString; @synthesize date = _date; -- (void)dealloc { +- (void)dealloc +{ [_testString release]; [_date release]; [super dealloc]; diff --git a/Tests/Models/RKMappableObject.h b/Tests/Models/RKMappableObject.h index 7abc4cb39d..e908ac069e 100644 --- a/Tests/Models/RKMappableObject.h +++ b/Tests/Models/RKMappableObject.h @@ -22,19 +22,19 @@ #import "RKMappableAssociation.h" @interface RKMappableObject : NSObject { - NSDate* _dateTest; - NSNumber* _numberTest; - NSString* _stringTest; - NSURL* _urlTest; - RKMappableAssociation* _hasOne; - NSSet* _hasMany; + NSDate *_dateTest; + NSNumber *_numberTest; + NSString *_stringTest; + NSURL *_urlTest; + RKMappableAssociation *_hasOne; + NSSet *_hasMany; } -@property (nonatomic, retain) NSDate* dateTest; -@property (nonatomic, retain) NSNumber* numberTest; -@property (nonatomic, retain) NSString* stringTest; -@property (nonatomic, retain) NSURL* urlTest; -@property (nonatomic, retain) RKMappableAssociation* hasOne; -@property (nonatomic, retain) NSSet* hasMany; +@property (nonatomic, retain) NSDate *dateTest; +@property (nonatomic, retain) NSNumber *numberTest; +@property (nonatomic, retain) NSString *stringTest; +@property (nonatomic, retain) NSURL *urlTest; +@property (nonatomic, retain) RKMappableAssociation *hasOne; +@property (nonatomic, retain) NSSet *hasMany; @end diff --git a/Tests/Models/RKObjectLoaderTestResultModel.h b/Tests/Models/RKObjectLoaderTestResultModel.h index 3ed220680f..c918c6da8d 100644 --- a/Tests/Models/RKObjectLoaderTestResultModel.h +++ b/Tests/Models/RKObjectLoaderTestResultModel.h @@ -21,13 +21,13 @@ #import @interface RKObjectLoaderTestResultModel : NSObject { - NSNumber* _ID; - NSDate* _endsAt; - NSString* _photoURL; + NSNumber *_ID; + NSDate *_endsAt; + NSString *_photoURL; } -@property (nonatomic, retain) NSNumber* ID; -@property (nonatomic, retain) NSDate* endsAt; -@property (nonatomic, retain) NSString* photoURL; +@property (nonatomic, retain) NSNumber *ID; +@property (nonatomic, retain) NSDate *endsAt; +@property (nonatomic, retain) NSString *photoURL; @end diff --git a/Tests/Models/RKObjectMapperTestModel.h b/Tests/Models/RKObjectMapperTestModel.h index c77b42d5ee..cd22bdd623 100644 --- a/Tests/Models/RKObjectMapperTestModel.h +++ b/Tests/Models/RKObjectMapperTestModel.h @@ -22,13 +22,13 @@ #import @interface RKObjectMapperTestModel : NSObject { - NSString* _name; - NSNumber* _age; - NSDate* _createdAt; + NSString *_name; + NSNumber *_age; + NSDate *_createdAt; } -@property (nonatomic,retain) NSString* name; -@property (nonatomic,retain) NSNumber* age; -@property (nonatomic,retain) NSDate* createdAt; +@property (nonatomic, retain) NSString *name; +@property (nonatomic, retain) NSNumber *age; +@property (nonatomic, retain) NSDate *createdAt; @end diff --git a/Tests/Models/RKResident.h b/Tests/Models/RKResident.h index 49ce278ce2..050663e9ce 100644 --- a/Tests/Models/RKResident.h +++ b/Tests/Models/RKResident.h @@ -26,10 +26,10 @@ @interface RKResident : NSManagedObject { } -@property (nonatomic, retain) NSString* residableType; -@property (nonatomic, retain) NSNumber* railsID; -@property (nonatomic, retain) NSNumber* residableId; -@property (nonatomic, retain) NSNumber* houseId; -@property (nonatomic, retain) RKHouse* house; +@property (nonatomic, retain) NSString *residableType; +@property (nonatomic, retain) NSNumber *railsID; +@property (nonatomic, retain) NSNumber *residableId; +@property (nonatomic, retain) NSNumber *houseId; +@property (nonatomic, retain) RKHouse *house; @end diff --git a/Tests/Models/RKSearchable.h b/Tests/Models/RKSearchable.h index c1e5f93530..453bda2860 100644 --- a/Tests/Models/RKSearchable.h +++ b/Tests/Models/RKSearchable.h @@ -24,7 +24,7 @@ @interface RKSearchable : RKSearchableManagedObject -@property (nonatomic, retain) NSString * title; -@property (nonatomic, retain) NSString * body; +@property (nonatomic, retain) NSString *title; +@property (nonatomic, retain) NSString *body; @end diff --git a/Tests/Models/RKSearchable.m b/Tests/Models/RKSearchable.m index 13c9501f40..bb7ad01f04 100644 --- a/Tests/Models/RKSearchable.m +++ b/Tests/Models/RKSearchable.m @@ -26,7 +26,8 @@ @implementation RKSearchable @dynamic title; @dynamic body; -+ (NSArray*)searchableAttributes { ++ (NSArray *)searchableAttributes +{ return [NSArray arrayWithObjects:@"title", @"body", nil]; } diff --git a/Tests/Models/RKTestAddress.h b/Tests/Models/RKTestAddress.h index 0cae94125b..95a6c5e3d9 100644 --- a/Tests/Models/RKTestAddress.h +++ b/Tests/Models/RKTestAddress.h @@ -9,17 +9,17 @@ #import @interface RKTestAddress : NSObject { - NSNumber* _addressID; - NSString* _city; - NSString* _state; - NSString* _country; + NSNumber *_addressID; + NSString *_city; + NSString *_state; + NSString *_country; } -@property (nonatomic, retain) NSNumber* addressID; -@property (nonatomic, retain) NSString* city; -@property (nonatomic, retain) NSString* state; -@property (nonatomic, retain) NSString* country; +@property (nonatomic, retain) NSNumber *addressID; +@property (nonatomic, retain) NSString *city; +@property (nonatomic, retain) NSString *state; +@property (nonatomic, retain) NSString *country; -+ (RKTestAddress*)address; ++ (RKTestAddress *)address; @end diff --git a/Tests/Models/RKTestAddress.m b/Tests/Models/RKTestAddress.m index e05865bbb3..e9c397f0b9 100644 --- a/Tests/Models/RKTestAddress.m +++ b/Tests/Models/RKTestAddress.m @@ -15,15 +15,17 @@ @implementation RKTestAddress @synthesize state = _state; @synthesize country = _country; -+ (RKTestAddress*)address { ++ (RKTestAddress *)address +{ return [[self new] autorelease]; } // isEqual: is consulted by the mapping operation // to determine if assocation values should be set -- (BOOL)isEqual:(id)object { +- (BOOL)isEqual:(id)object +{ if ([object isKindOfClass:[RKTestAddress class]]) { - return [[(RKTestAddress*)object addressID] isEqualToNumber:self.addressID]; + return [[(RKTestAddress *)object addressID] isEqualToNumber:self.addressID]; } else { return NO; } diff --git a/Tests/Models/RKTestUser.h b/Tests/Models/RKTestUser.h index 528cb7d34f..21b2b1328e 100644 --- a/Tests/Models/RKTestUser.h +++ b/Tests/Models/RKTestUser.h @@ -10,40 +10,40 @@ #import "RKTestAddress.h" @interface RKTestUser : NSObject { - NSNumber* _userID; - NSString* _name; - NSDate* _birthDate; - NSArray* _favoriteColors; - NSDictionary* _addressDictionary; - NSURL* _website; - NSNumber* _isDeveloper; - NSNumber* _luckyNumber; - NSDecimalNumber* _weight; - NSArray* _interests; - NSString* _country; + NSNumber *_userID; + NSString *_name; + NSDate *_birthDate; + NSArray *_favoriteColors; + NSDictionary *_addressDictionary; + NSURL *_website; + NSNumber *_isDeveloper; + NSNumber *_luckyNumber; + NSDecimalNumber *_weight; + NSArray *_interests; + NSString *_country; // Relationships - RKTestAddress* _address; - NSArray* _friends; + RKTestAddress *_address; + NSArray *_friends; } -@property (nonatomic, retain) NSNumber* userID; -@property (nonatomic, retain) NSString* name; -@property (nonatomic, retain) NSDate* birthDate; +@property (nonatomic, retain) NSNumber *userID; +@property (nonatomic, retain) NSString *name; +@property (nonatomic, retain) NSDate *birthDate; @property (nonatomic, retain) NSDate *favoriteDate; -@property (nonatomic, retain) NSArray* favoriteColors; -@property (nonatomic, retain) NSDictionary* addressDictionary; -@property (nonatomic, retain) NSURL* website; -@property (nonatomic, retain) NSNumber* isDeveloper; -@property (nonatomic, retain) NSNumber* luckyNumber; -@property (nonatomic, retain) NSDecimalNumber* weight; -@property (nonatomic, retain) NSArray* interests; -@property (nonatomic, retain) NSString* country; -@property (nonatomic, retain) RKTestAddress* address; -@property (nonatomic, retain) NSArray* friends; -@property (nonatomic, retain) NSSet* friendsSet; +@property (nonatomic, retain) NSArray *favoriteColors; +@property (nonatomic, retain) NSDictionary *addressDictionary; +@property (nonatomic, retain) NSURL *website; +@property (nonatomic, retain) NSNumber *isDeveloper; +@property (nonatomic, retain) NSNumber *luckyNumber; +@property (nonatomic, retain) NSDecimalNumber *weight; +@property (nonatomic, retain) NSArray *interests; +@property (nonatomic, retain) NSString *country; +@property (nonatomic, retain) RKTestAddress *address; +@property (nonatomic, retain) NSArray *friends; +@property (nonatomic, retain) NSSet *friendsSet; @property (nonatomic, retain) NSOrderedSet *friendsOrderedSet; -+ (RKTestUser*)user; ++ (RKTestUser *)user; @end diff --git a/Tests/Models/RKTestUser.m b/Tests/Models/RKTestUser.m index ddb5689f77..1c7707116b 100644 --- a/Tests/Models/RKTestUser.m +++ b/Tests/Models/RKTestUser.m @@ -28,31 +28,35 @@ @implementation RKTestUser @synthesize friendsSet = _friendsSet; @synthesize friendsOrderedSet = _friendsOrderedSet; -+ (RKTestUser*)user { ++ (RKTestUser *)user +{ return [[self new] autorelease]; } // isEqual: is consulted by the mapping operation // to determine if assocation values should be set -- (BOOL)isEqual:(id)object { +- (BOOL)isEqual:(id)object +{ if ([object isKindOfClass:[RKTestUser class]]) { - if ([(RKTestUser*)object userID] == nil && self.userID == nil) { + if ([(RKTestUser *)object userID] == nil && self.userID == nil) { // No primary key -- consult superclass return [super isEqual:object]; } else { - return [[(RKTestUser*)object userID] isEqualToNumber:self.userID]; + return [[(RKTestUser *)object userID] isEqualToNumber:self.userID]; } } return NO; } -- (id)valueForUndefinedKey:(NSString *)key { +- (id)valueForUndefinedKey:(NSString *)key +{ RKLogError(@"Unexpectedly asked for undefined key '%@'", key); return [super valueForUndefinedKey:key]; } -- (void)setValue:(id)value forUndefinedKey:(NSString *)key { +- (void)setValue:(id)value forUndefinedKey:(NSString *)key +{ RKLogError(@"Asked to set value '%@' for undefined key '%@'", value, key); [super setValue:value forUndefinedKey:key]; } diff --git a/Tests/RKTestEnvironment.h b/Tests/RKTestEnvironment.h index 132ba8343f..2bbc44d519 100644 --- a/Tests/RKTestEnvironment.h +++ b/Tests/RKTestEnvironment.h @@ -29,7 +29,7 @@ #import #import -RKOAuthClient* RKTestNewOAuthClient(RKTestResponseLoader* loader); +RKOAuthClient *RKTestNewOAuthClient(RKTestResponseLoader *loader); /* Base class for RestKit test cases. Provides initialization of testing diff --git a/Tests/RKTestEnvironment.m b/Tests/RKTestEnvironment.m index 40b7d7086d..2a21365681 100644 --- a/Tests/RKTestEnvironment.m +++ b/Tests/RKTestEnvironment.m @@ -22,7 +22,7 @@ #import "RKTestEnvironment.h" #import "RKParserRegistry.h" -RKOAuthClient* RKTestNewOAuthClient(RKTestResponseLoader* loader) +RKOAuthClient *RKTestNewOAuthClient(RKTestResponseLoader *loader) { [loader setTimeout:10]; RKOAuthClient *client = [RKOAuthClient clientWithClientID:@"4fa42a4a7184796662000001" secret:@"restkit_secret"]; diff --git a/VERSION b/VERSION index 571215736a..42624f314e 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.10.1 +0.10.2 \ No newline at end of file diff --git a/Vendor/JSONKit/JSONKit.m b/Vendor/JSONKit/JSONKit.m index b9488b20d5..520b4be91e 100644 --- a/Vendor/JSONKit/JSONKit.m +++ b/Vendor/JSONKit/JSONKit.m @@ -175,7 +175,7 @@ The code in isValidCodePoint() is derived from the ICU code in #define JK_CACHE_SLOTS (1UL << JK_CACHE_SLOTS_BITS) // JK_CACHE_PROBES is the number of probe attempts. #define JK_CACHE_PROBES (4UL) -// JK_INIT_CACHE_AGE must be (1 << AGE) - 1 +// JK_INIT_CACHE_AGE must be < (1 << AGE) - 1, where AGE is sizeof(typeof(AGE)) * 8. #define JK_INIT_CACHE_AGE (0) // JK_TOKENBUFFER_SIZE is the default stack size for the temporary buffer used to hold "non-simple" strings (i.e., contains \ escapes) @@ -609,7 +609,7 @@ - (void)releaseState; JK_STATIC_INLINE size_t jk_min(size_t a, size_t b); JK_STATIC_INLINE size_t jk_max(size_t a, size_t b); -JK_STATIC_INLINE JKHash calculateHash(JKHash currentHash, unsigned char c); +JK_STATIC_INLINE JKHash jk_calculateHash(JKHash currentHash, unsigned char c); // JSONKit v1.4 used both a JKArray : NSArray and JKMutableArray : NSMutableArray, and the same for the dictionary collection type. // However, Louis Gerbarg (via cocoa-dev) pointed out that Cocoa / Core Foundation actually implements only a single class that inherits from the @@ -742,14 +742,14 @@ - (NSUInteger)count - (void)getObjects:(id *)objectsPtr range:(NSRange)range { NSParameterAssert((objects != NULL) && (count <= capacity)); - if((objectsPtr == NULL) && (NSMaxRange(range) > 0UL)) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: pointer to objects array is NULL but range length is %lu", NSStringFromClass([self class]), NSStringFromSelector(_cmd), NSMaxRange(range)]; } - if((range.location > count) || (NSMaxRange(range) > count)) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), NSMaxRange(range), count]; } + if((objectsPtr == NULL) && (NSMaxRange(range) > 0UL)) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: pointer to objects array is NULL but range length is %lu", NSStringFromClass([self class]), NSStringFromSelector(_cmd), (unsigned long)NSMaxRange(range)]; } + if((range.location > count) || (NSMaxRange(range) > count)) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), (unsigned long)NSMaxRange(range), (unsigned long)count]; } memcpy(objectsPtr, objects + range.location, range.length * sizeof(id)); } - (id)objectAtIndex:(NSUInteger)objectIndex { - if(objectIndex >= count) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), objectIndex, count]; } + if(objectIndex >= count) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), (unsigned long)objectIndex, (unsigned long)count]; } NSParameterAssert((objects != NULL) && (count <= capacity) && (objects[objectIndex] != NULL)); return(objects[objectIndex]); } @@ -770,7 +770,7 @@ - (void)insertObject:(id)anObject atIndex:(NSUInteger)objectIndex { if(mutations == 0UL) { [NSException raise:NSInternalInconsistencyException format:@"*** -[%@ %@]: mutating method sent to immutable object", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; } if(anObject == NULL) { [NSException raise:NSInvalidArgumentException format:@"*** -[%@ %@]: attempt to insert nil", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; } - if(objectIndex > count) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), objectIndex, count + 1UL]; } + if(objectIndex > count) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), (unsigned long)objectIndex, (unsigned long)(count + 1UL)]; } #ifdef __clang_analyzer__ [anObject retain]; // Stupid clang analyzer... Issue #19. #else @@ -783,7 +783,7 @@ - (void)insertObject:(id)anObject atIndex:(NSUInteger)objectIndex - (void)removeObjectAtIndex:(NSUInteger)objectIndex { if(mutations == 0UL) { [NSException raise:NSInternalInconsistencyException format:@"*** -[%@ %@]: mutating method sent to immutable object", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; } - if(objectIndex >= count) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), objectIndex, count]; } + if(objectIndex >= count) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), (unsigned long)objectIndex, (unsigned long)count]; } _JKArrayRemoveObjectAtIndex(self, objectIndex); mutations = (mutations == NSUIntegerMax) ? 1UL : mutations + 1UL; } @@ -792,7 +792,7 @@ - (void)replaceObjectAtIndex:(NSUInteger)objectIndex withObject:(id)anObject { if(mutations == 0UL) { [NSException raise:NSInternalInconsistencyException format:@"*** -[%@ %@]: mutating method sent to immutable object", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; } if(anObject == NULL) { [NSException raise:NSInvalidArgumentException format:@"*** -[%@ %@]: attempt to insert nil", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; } - if(objectIndex >= count) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), objectIndex, count]; } + if(objectIndex >= count) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), (unsigned long)objectIndex, (unsigned long)count]; } #ifdef __clang_analyzer__ [anObject retain]; // Stupid clang analyzer... Issue #19. #else @@ -848,7 +848,7 @@ - (void)dealloc - (NSArray *)allObjects { NSParameterAssert(collection != NULL); - NSUInteger count = [collection count], atObject = 0UL; + NSUInteger count = [(NSDictionary *)collection count], atObject = 0UL; id objects[count]; while((objects[atObject] = [self nextObject]) != NULL) { NSParameterAssert(atObject < count); atObject++; } @@ -896,7 +896,7 @@ + (id)allocWithZone:(NSZone *)zone }; static NSUInteger _JKDictionaryCapacityForCount(NSUInteger count) { - NSUInteger bottom = 0UL, top = sizeof(jk_dictionaryCapacities) / sizeof(NSUInteger), mid = 0UL, tableSize = lround(floor((count) * 1.33)); + NSUInteger bottom = 0UL, top = sizeof(jk_dictionaryCapacities) / sizeof(NSUInteger), mid = 0UL, tableSize = (NSUInteger)lround(floor(((double)count) * 1.33)); while(top > bottom) { mid = (top + bottom) / 2UL; if(jk_dictionaryCapacities[mid] < tableSize) { bottom = mid + 1UL; } else { top = mid; } } return(jk_dictionaryCapacities[bottom]); } @@ -1111,7 +1111,8 @@ - (id)mutableCopyWithZone:(NSZone *)zone JK_STATIC_INLINE size_t jk_min(size_t a, size_t b) { return((a < b) ? a : b); } JK_STATIC_INLINE size_t jk_max(size_t a, size_t b) { return((a > b) ? a : b); } -JK_STATIC_INLINE JKHash calculateHash(JKHash currentHash, unsigned char c) { return(((currentHash << 5) + currentHash) + c); } +JK_STATIC_INLINE JKHash jk_calculateHash(JKHash currentHash, unsigned char c) { return((((currentHash << 5) + currentHash) + (c - 29)) ^ (currentHash >> 19)); } + static void jk_error(JKParseState *parseState, NSString *format, ...) { NSCParameterAssert((parseState != NULL) && (format != NULL)); @@ -1408,7 +1409,7 @@ JK_STATIC_INLINE int jk_string_add_unicodeCodePoint(JKParseState *parseState, ui if((result = ConvertUTF32toUTF8(unicodeCodePoint, &u8s, (parseState->token.tokenBuffer.bytes.ptr + parseState->token.tokenBuffer.bytes.length))) != conversionOK) { if(result == targetExhausted) { return(1); } } size_t utf8len = u8s - &parseState->token.tokenBuffer.bytes.ptr[*tokenBufferIdx], nextIdx = (*tokenBufferIdx) + utf8len; - while(*tokenBufferIdx < nextIdx) { *stringHash = calculateHash(*stringHash, parseState->token.tokenBuffer.bytes.ptr[(*tokenBufferIdx)++]); } + while(*tokenBufferIdx < nextIdx) { *stringHash = jk_calculateHash(*stringHash, parseState->token.tokenBuffer.bytes.ptr[(*tokenBufferIdx)++]); } return(0); } @@ -1442,8 +1443,8 @@ static int jk_parse_string(JKParseState *parseState) { ConversionResult result; if(JK_EXPECT_F((result = ConvertSingleCodePointInUTF8(atStringCharacter - 1, endOfBuffer, (UTF8 const **)&nextValidCharacter, &u32ch)) != conversionOK)) { goto switchToSlowPath; } - stringHash = calculateHash(stringHash, currentChar); - while(atStringCharacter < nextValidCharacter) { NSCParameterAssert(JK_AT_STRING_PTR(parseState) <= JK_END_STRING_PTR(parseState)); stringHash = calculateHash(stringHash, *atStringCharacter++); } + stringHash = jk_calculateHash(stringHash, currentChar); + while(atStringCharacter < nextValidCharacter) { NSCParameterAssert(JK_AT_STRING_PTR(parseState) <= JK_END_STRING_PTR(parseState)); stringHash = jk_calculateHash(stringHash, *atStringCharacter++); } continue; } else { if(JK_EXPECT_F(currentChar == (unsigned long)'"')) { stringState = JSONStringStateFinished; goto finishedParsing; } @@ -1460,7 +1461,7 @@ static int jk_parse_string(JKParseState *parseState) { if(JK_EXPECT_F(currentChar < 0x20UL)) { jk_error(parseState, @"Invalid character < 0x20 found in string: 0x%2.2x.", currentChar); stringState = JSONStringStateError; goto finishedParsing; } - stringHash = calculateHash(stringHash, currentChar); + stringHash = jk_calculateHash(stringHash, currentChar); } } @@ -1478,7 +1479,7 @@ static int jk_parse_string(JKParseState *parseState) { if(JK_EXPECT_T(currentChar < (unsigned long)0x80)) { // Not a UTF8 sequence if(JK_EXPECT_F(currentChar == (unsigned long)'"')) { stringState = JSONStringStateFinished; atStringCharacter++; goto finishedParsing; } if(JK_EXPECT_F(currentChar == (unsigned long)'\\')) { stringState = JSONStringStateEscape; continue; } - stringHash = calculateHash(stringHash, currentChar); + stringHash = jk_calculateHash(stringHash, currentChar); tokenBuffer[tokenBufferIdx++] = currentChar; continue; } else { // UTF8 sequence @@ -1493,7 +1494,7 @@ static int jk_parse_string(JKParseState *parseState) { atStringCharacter = nextValidCharacter - 1; continue; } else { - while(atStringCharacter < nextValidCharacter) { tokenBuffer[tokenBufferIdx++] = *atStringCharacter; stringHash = calculateHash(stringHash, *atStringCharacter++); } + while(atStringCharacter < nextValidCharacter) { tokenBuffer[tokenBufferIdx++] = *atStringCharacter; stringHash = jk_calculateHash(stringHash, *atStringCharacter++); } atStringCharacter--; continue; } @@ -1521,7 +1522,7 @@ static int jk_parse_string(JKParseState *parseState) { parsedEscapedChar: stringState = JSONStringStateParsing; - stringHash = calculateHash(stringHash, escapedChar); + stringHash = jk_calculateHash(stringHash, escapedChar); tokenBuffer[tokenBufferIdx++] = escapedChar; break; @@ -1709,7 +1710,7 @@ static int jk_parse_number(JKParseState *parseState) { if(JK_EXPECT_F(endOfNumber != &numberTempBuf[parseState->token.tokenPtrRange.length]) && JK_EXPECT_F(numberState != JSONNumberStateError)) { numberState = JSONNumberStateError; jk_error(parseState, @"The conversion function did not consume all of the number tokens characters."); } size_t hashIndex = 0UL; - for(hashIndex = 0UL; hashIndex < parseState->token.value.ptrRange.length; hashIndex++) { parseState->token.value.hash = calculateHash(parseState->token.value.hash, parseState->token.value.ptrRange.ptr[hashIndex]); } + for(hashIndex = 0UL; hashIndex < parseState->token.value.ptrRange.length; hashIndex++) { parseState->token.value.hash = jk_calculateHash(parseState->token.value.hash, parseState->token.value.ptrRange.ptr[hashIndex]); } } if(JK_EXPECT_F(numberState != JSONNumberStateFinished)) { jk_error(parseState, @"Invalid number."); } @@ -1972,7 +1973,7 @@ static id json_parse_it(JKParseState *parseState) { #pragma mark Object cache // This uses a Galois Linear Feedback Shift Register (LFSR) PRNG to pick which item in the cache to age. It has a period of (2^32)-1. -// NOTE: A LFSR *MUST* be initialized to a non-zero value and must always have a non-zero value. +// NOTE: A LFSR *MUST* be initialized to a non-zero value and must always have a non-zero value. The LFSR is initalized to 1 in -initWithParseOptions: JK_STATIC_INLINE void jk_cache_age(JKParseState *parseState) { NSCParameterAssert((parseState != NULL) && (parseState->cache.prng_lfsr != 0U)); parseState->cache.prng_lfsr = (parseState->cache.prng_lfsr >> 1) ^ ((0U - (parseState->cache.prng_lfsr & 1U)) & 0x80200003U); @@ -1983,9 +1984,8 @@ JK_STATIC_INLINE void jk_cache_age(JKParseState *parseState) { // // The hash table is a linear C array of JKTokenCacheItem. The terms "item" and "bucket" are synonymous with the index in to the cache array, i.e. cache.items[bucket]. // -// Items in the cache have an age associated with them. The age is the number of rightmost 1 bits, i.e. 0000 = 0, 0001 = 1, 0011 = 2, 0111 = 3, 1111 = 4. -// This allows us to use left and right shifts to add or subtract from an items age. Add = (age << 1) | 1. Subtract = age >> 0. Subtract is synonymous with "age" (i.e., age an item). -// The reason for this is it allows us to perform saturated adds and subtractions and is branchless. +// Items in the cache have an age associated with them. An items age is incremented using saturating unsigned arithmetic and decremeted using unsigned right shifts. +// Thus, an items age is managed using an AIMD policy- additive increase, multiplicative decrease. All age calculations and manipulations are branchless. // The primitive C type MUST be unsigned. It is currently a "char", which allows (at a minimum and in practice) 8 bits. // // A "useable bucket" is a bucket that is not in use (never populated), or has an age == 0. @@ -2000,12 +2000,12 @@ JK_STATIC_INLINE void jk_cache_age(JKParseState *parseState) { void *parsedAtom = NULL; if(JK_EXPECT_F(parseState->token.value.ptrRange.length == 0UL) && JK_EXPECT_T(parseState->token.value.type == JKValueTypeString)) { return(@""); } - + for(x = 0UL; x < JK_CACHE_PROBES; x++) { if(JK_EXPECT_F(parseState->cache.items[bucket].object == NULL)) { setBucket = 1UL; useableBucket = bucket; break; } if((JK_EXPECT_T(parseState->cache.items[bucket].hash == parseState->token.value.hash)) && (JK_EXPECT_T(parseState->cache.items[bucket].size == parseState->token.value.ptrRange.length)) && (JK_EXPECT_T(parseState->cache.items[bucket].type == parseState->token.value.type)) && (JK_EXPECT_T(parseState->cache.items[bucket].bytes != NULL)) && (JK_EXPECT_T(memcmp(parseState->cache.items[bucket].bytes, parseState->token.value.ptrRange.ptr, parseState->token.value.ptrRange.length) == 0U))) { - parseState->cache.age[bucket] = (parseState->cache.age[bucket] << 1) | 1U; + parseState->cache.age[bucket] = (((uint32_t)parseState->cache.age[bucket]) + 1U) - (((((uint32_t)parseState->cache.age[bucket]) + 1U) >> 31) ^ 1U); parseState->token.value.cacheItem = &parseState->cache.items[bucket]; NSCParameterAssert(parseState->cache.items[bucket].object != NULL); return((void *)CFRetain(parseState->cache.items[bucket].object)); @@ -2592,21 +2592,23 @@ static int jk_encode_add_atom_to_buffer(JKEncodeState *encodeState, void *object // // XXX XXX XXX XXX - BOOL workAroundMacOSXABIBreakingBug = NO; - if(JK_EXPECT_F(((NSUInteger)object) & 0x1)) { workAroundMacOSXABIBreakingBug = YES; goto slowClassLookup; } - if(JK_EXPECT_T(object->isa == encodeState->fastClassLookup.stringClass)) { isClass = JKClassString; } - else if(JK_EXPECT_T(object->isa == encodeState->fastClassLookup.numberClass)) { isClass = JKClassNumber; } - else if(JK_EXPECT_T(object->isa == encodeState->fastClassLookup.dictionaryClass)) { isClass = JKClassDictionary; } - else if(JK_EXPECT_T(object->isa == encodeState->fastClassLookup.arrayClass)) { isClass = JKClassArray; } - else if(JK_EXPECT_T(object->isa == encodeState->fastClassLookup.nullClass)) { isClass = JKClassNull; } + BOOL workAroundMacOSXABIBreakingBug = (JK_EXPECT_F(((NSUInteger)object) & 0x1)) ? YES : NO; + void *objectISA = (JK_EXPECT_F(workAroundMacOSXABIBreakingBug)) ? NULL : *((void **)objectPtr); + if(JK_EXPECT_F(workAroundMacOSXABIBreakingBug)) { goto slowClassLookup; } + + if(JK_EXPECT_T(objectISA == encodeState->fastClassLookup.stringClass)) { isClass = JKClassString; } + else if(JK_EXPECT_T(objectISA == encodeState->fastClassLookup.numberClass)) { isClass = JKClassNumber; } + else if(JK_EXPECT_T(objectISA == encodeState->fastClassLookup.dictionaryClass)) { isClass = JKClassDictionary; } + else if(JK_EXPECT_T(objectISA == encodeState->fastClassLookup.arrayClass)) { isClass = JKClassArray; } + else if(JK_EXPECT_T(objectISA == encodeState->fastClassLookup.nullClass)) { isClass = JKClassNull; } else { slowClassLookup: - if(JK_EXPECT_T([object isKindOfClass:[NSString class]])) { if(workAroundMacOSXABIBreakingBug == NO) { encodeState->fastClassLookup.stringClass = object->isa; } isClass = JKClassString; } - else if(JK_EXPECT_T([object isKindOfClass:[NSNumber class]])) { if(workAroundMacOSXABIBreakingBug == NO) { encodeState->fastClassLookup.numberClass = object->isa; } isClass = JKClassNumber; } - else if(JK_EXPECT_T([object isKindOfClass:[NSDictionary class]])) { if(workAroundMacOSXABIBreakingBug == NO) { encodeState->fastClassLookup.dictionaryClass = object->isa; } isClass = JKClassDictionary; } - else if(JK_EXPECT_T([object isKindOfClass:[NSArray class]])) { if(workAroundMacOSXABIBreakingBug == NO) { encodeState->fastClassLookup.arrayClass = object->isa; } isClass = JKClassArray; } - else if(JK_EXPECT_T([object isKindOfClass:[NSNull class]])) { if(workAroundMacOSXABIBreakingBug == NO) { encodeState->fastClassLookup.nullClass = object->isa; } isClass = JKClassNull; } + if(JK_EXPECT_T([object isKindOfClass:[NSString class]])) { if(workAroundMacOSXABIBreakingBug == NO) { encodeState->fastClassLookup.stringClass = objectISA; } isClass = JKClassString; } + else if(JK_EXPECT_T([object isKindOfClass:[NSNumber class]])) { if(workAroundMacOSXABIBreakingBug == NO) { encodeState->fastClassLookup.numberClass = objectISA; } isClass = JKClassNumber; } + else if(JK_EXPECT_T([object isKindOfClass:[NSDictionary class]])) { if(workAroundMacOSXABIBreakingBug == NO) { encodeState->fastClassLookup.dictionaryClass = objectISA; } isClass = JKClassDictionary; } + else if(JK_EXPECT_T([object isKindOfClass:[NSArray class]])) { if(workAroundMacOSXABIBreakingBug == NO) { encodeState->fastClassLookup.arrayClass = objectISA; } isClass = JKClassArray; } + else if(JK_EXPECT_T([object isKindOfClass:[NSNull class]])) { if(workAroundMacOSXABIBreakingBug == NO) { encodeState->fastClassLookup.nullClass = objectISA; } isClass = JKClassNull; } else { if((rerunningAfterClassFormatter == NO) && ( #ifdef __BLOCKS__ @@ -2788,7 +2790,8 @@ static int jk_encode_add_atom_to_buffer(JKEncodeState *encodeState, void *object for(id keyObject in enumerateObject) { if(JK_EXPECT_T(printComma)) { if(JK_EXPECT_F(jk_encode_write1(encodeState, 0L, ","))) { return(1); } } printComma = 1; - if(JK_EXPECT_F((keyObject->isa != encodeState->fastClassLookup.stringClass)) && JK_EXPECT_F(([keyObject isKindOfClass:[NSString class]] == NO))) { jk_encode_error(encodeState, @"Key must be a string object."); return(1); } + void *keyObjectISA = *((void **)keyObject); + if(JK_EXPECT_F((keyObjectISA != encodeState->fastClassLookup.stringClass)) && JK_EXPECT_F(([keyObject isKindOfClass:[NSString class]] == NO))) { jk_encode_error(encodeState, @"Key must be a string object."); return(1); } if(JK_EXPECT_F(jk_encode_add_atom_to_buffer(encodeState, keyObject))) { return(1); } if(JK_EXPECT_F(jk_encode_write1(encodeState, 0L, ":"))) { return(1); } if(JK_EXPECT_F(jk_encode_add_atom_to_buffer(encodeState, (void *)CFDictionaryGetValue((CFDictionaryRef)object, keyObject)))) { return(1); } @@ -2799,7 +2802,8 @@ static int jk_encode_add_atom_to_buffer(JKEncodeState *encodeState, void *object for(idx = 0L; idx < dictionaryCount; idx++) { if(JK_EXPECT_T(printComma)) { if(JK_EXPECT_F(jk_encode_write1(encodeState, 0L, ","))) { return(1); } } printComma = 1; - if(JK_EXPECT_F(((id)keys[idx])->isa != encodeState->fastClassLookup.stringClass) && JK_EXPECT_F([(id)keys[idx] isKindOfClass:[NSString class]] == NO)) { jk_encode_error(encodeState, @"Key must be a string object."); return(1); } + void *keyObjectISA = *((void **)keys[idx]); + if(JK_EXPECT_F(keyObjectISA != encodeState->fastClassLookup.stringClass) && JK_EXPECT_F([(id)keys[idx] isKindOfClass:[NSString class]] == NO)) { jk_encode_error(encodeState, @"Key must be a string object."); return(1); } if(JK_EXPECT_F(jk_encode_add_atom_to_buffer(encodeState, keys[idx]))) { return(1); } if(JK_EXPECT_F(jk_encode_write1(encodeState, 0L, ":"))) { return(1); } if(JK_EXPECT_F(jk_encode_add_atom_to_buffer(encodeState, objects[idx]))) { return(1); } diff --git a/Vendor/cocoa-oauth/GCOAuth.h b/Vendor/cocoa-oauth/GCOAuth.h index b9495de453..cdc54a5521 100644 --- a/Vendor/cocoa-oauth/GCOAuth.h +++ b/Vendor/cocoa-oauth/GCOAuth.h @@ -57,26 +57,15 @@ */ + (void)setHTTPShouldHandleCookies:(BOOL)handle; -/* - Creates and returns a URL request that will perform a GET HTTP operation. All +/** + Creates and returns a URL request that will perform an HTTP operation for the given method. All of the appropriate fields will be parameter encoded as necessary so do not encode them yourself. The contents of the parameters dictionary must be string key/value pairs. You are contracted to consume the NSURLRequest *immediately*. */ + (NSURLRequest *)URLRequestForPath:(NSString *)path - GETParameters:(NSDictionary *)parameters - host:(NSString *)host - consumerKey:(NSString *)consumerKey - consumerSecret:(NSString *)consumerSecret - accessToken:(NSString *)accessToken - tokenSecret:(NSString *)tokenSecret; - -/* - Performs the same operation as the above method but allows a customizable URL - scheme, e.g. HTTPS. - */ -+ (NSURLRequest *)URLRequestForPath:(NSString *)path - GETParameters:(NSDictionary *)parameters + HTTPMethod:(NSString *)HTTPMethod + parameters:(NSDictionary *)parameters scheme:(NSString *)scheme host:(NSString *)host consumerKey:(NSString *)consumerKey @@ -85,12 +74,13 @@ tokenSecret:(NSString *)tokenSecret; /* - Creates and returns a URL request that will perform a POST HTTP operation. All - data will be sent as form URL encoded. Restrictions on the arguments to this - method are the same as the GET request methods. + Creates and returns a URL request that will perform a GET HTTP operation. All + of the appropriate fields will be parameter encoded as necessary so do not + encode them yourself. The contents of the parameters dictionary must be string + key/value pairs. You are contracted to consume the NSURLRequest *immediately*. */ + (NSURLRequest *)URLRequestForPath:(NSString *)path - POSTParameters:(NSDictionary *)parameters + GETParameters:(NSDictionary *)parameters host:(NSString *)host consumerKey:(NSString *)consumerKey consumerSecret:(NSString *)consumerSecret @@ -102,7 +92,7 @@ scheme, e.g. HTTPS. */ + (NSURLRequest *)URLRequestForPath:(NSString *)path - POSTParameters:(NSDictionary *)parameters + GETParameters:(NSDictionary *)parameters scheme:(NSString *)scheme host:(NSString *)host consumerKey:(NSString *)consumerKey @@ -111,12 +101,12 @@ tokenSecret:(NSString *)tokenSecret; /* - Creates and returns a URL request that will perform a PUT HTTPS operation. All + Creates and returns a URL request that will perform a POST HTTP operation. All data will be sent as form URL encoded. Restrictions on the arguments to this method are the same as the GET request methods. */ + (NSURLRequest *)URLRequestForPath:(NSString *)path - PUTParameters:(NSDictionary *)parameters + POSTParameters:(NSDictionary *)parameters host:(NSString *)host consumerKey:(NSString *)consumerKey consumerSecret:(NSString *)consumerSecret @@ -128,7 +118,7 @@ scheme, e.g. HTTPS. */ + (NSURLRequest *)URLRequestForPath:(NSString *)path - PUTParameters:(NSDictionary *)parameters + POSTParameters:(NSDictionary *)parameters scheme:(NSString *)scheme host:(NSString *)host consumerKey:(NSString *)consumerKey diff --git a/Vendor/cocoa-oauth/GCOAuth.m b/Vendor/cocoa-oauth/GCOAuth.m index 94d247a280..f2f4a22415 100644 --- a/Vendor/cocoa-oauth/GCOAuth.m +++ b/Vendor/cocoa-oauth/GCOAuth.m @@ -75,17 +75,6 @@ - (NSString *)signature; // generate signature base - (NSString *)signatureBase; - -// method can be PUT, POST or DELETE. but not GET -+ (NSURLRequest *)URLRequestForPath:(NSString *)path - urlMethod:(NSString *)urlMethod - parameters:(NSDictionary *)parameters - scheme:(NSString *)scheme - host:(NSString *)host - consumerKey:(NSString *)consumerKey - consumerSecret:(NSString *)consumerSecret - accessToken:(NSString *)accessToken - tokenSecret:(NSString *)tokenSecret; @end @implementation GCOAuth @@ -221,7 +210,7 @@ + (NSString *)timeStamp { time_t t; time(&t); mktime(gmtime(&t)); - return [NSString stringWithFormat:@"%u", (t + GCOAuthTimeStampOffset)]; + return [NSString stringWithFormat:@"%lu", (t + GCOAuthTimeStampOffset)]; } + (NSString *)queryStringFromParameters:(NSDictionary *)parameters { NSMutableArray *entries = [NSMutableArray array]; @@ -232,30 +221,14 @@ + (NSString *)queryStringFromParameters:(NSDictionary *)parameters { return [entries componentsJoinedByString:@"&"]; } + (NSURLRequest *)URLRequestForPath:(NSString *)path - GETParameters:(NSDictionary *)parameters - host:(NSString *)host - consumerKey:(NSString *)consumerKey - consumerSecret:(NSString *)consumerSecret - accessToken:(NSString *)accessToken - tokenSecret:(NSString *)tokenSecret { - return [self URLRequestForPath:path - GETParameters:parameters - scheme:@"http" - host:host - consumerKey:consumerKey - consumerSecret:consumerSecret - accessToken:accessToken - tokenSecret:tokenSecret]; -} -+ (NSURLRequest *)URLRequestForPath:(NSString *)path - GETParameters:(NSDictionary *)parameters + HTTPMethod:(NSString *)HTTPMethod + parameters:(NSDictionary *)parameters scheme:(NSString *)scheme host:(NSString *)host consumerKey:(NSString *)consumerKey consumerSecret:(NSString *)consumerSecret accessToken:(NSString *)accessToken tokenSecret:(NSString *)tokenSecret { - // check parameters if (host == nil || path == nil) { return nil; } @@ -264,46 +237,58 @@ + (NSURLRequest *)URLRequestForPath:(NSString *)path consumerSecret:consumerSecret accessToken:accessToken tokenSecret:tokenSecret]; - oauth.HTTPMethod = @"GET"; + oauth.HTTPMethod = HTTPMethod; oauth.requestParameters = parameters; + + if ([[HTTPMethod uppercaseString] isEqualToString:@"GET"]) { + // Handle GET + NSString *encodedPath = [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + NSString *URLString = [NSString stringWithFormat:@"%@://%@%@", scheme, host, encodedPath]; + if ([oauth.requestParameters count]) { + NSString *query = [GCOAuth queryStringFromParameters:oauth.requestParameters]; + URLString = [NSString stringWithFormat:@"%@?%@", URLString, query]; + } + oauth.URL = [NSURL URLWithString:URLString]; + } else { + // All other HTTP methods + NSURL *URL = [[NSURL alloc] initWithScheme:scheme host:host path:path]; + oauth.URL = URL; + [URL release]; + } - // create url - NSString *encodedPath = [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; - NSString *URLString = [NSString stringWithFormat:@"%@://%@%@", scheme, host, encodedPath]; - if ([oauth.requestParameters count]) { + NSMutableURLRequest *request = [oauth request]; + if (![[HTTPMethod uppercaseString] isEqualToString:@"GET"] && [oauth.requestParameters count]) { + // Add the parameters to the request body for non GET requests NSString *query = [GCOAuth queryStringFromParameters:oauth.requestParameters]; - URLString = [NSString stringWithFormat:@"%@?%@", URLString, query]; + NSData *data = [query dataUsingEncoding:NSUTF8StringEncoding]; + NSString *length = [NSString stringWithFormat:@"%lu", (unsigned long)[data length]]; + [request setHTTPBody:data]; + [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; + [request setValue:length forHTTPHeaderField:@"Content-Length"]; } - oauth.URL = [NSURL URLWithString:URLString]; // return - NSURLRequest *request = [oauth request]; [oauth release]; return request; - } - + (NSURLRequest *)URLRequestForPath:(NSString *)path - POSTParameters:(NSDictionary *)parameters + GETParameters:(NSDictionary *)parameters host:(NSString *)host consumerKey:(NSString *)consumerKey consumerSecret:(NSString *)consumerSecret accessToken:(NSString *)accessToken - tokenSecret:(NSString *)tokenSecret -{ - return [self URLRequestForPath:path - POSTParameters:parameters - scheme:@"https" - host:host - consumerKey:consumerKey - consumerSecret:consumerSecret - accessToken:accessToken + tokenSecret:(NSString *)tokenSecret { + return [self URLRequestForPath:path HTTPMethod:@"GET" + parameters:parameters + scheme:@"http" + host:host + consumerKey:consumerKey + consumerSecret:consumerSecret + accessToken:accessToken tokenSecret:tokenSecret]; } - - + (NSURLRequest *)URLRequestForPath:(NSString *)path - POSTParameters:(NSDictionary *)parameters + GETParameters:(NSDictionary *)parameters scheme:(NSString *)scheme host:(NSString *)host consumerKey:(NSString *)consumerKey @@ -311,38 +296,36 @@ + (NSURLRequest *)URLRequestForPath:(NSString *)path accessToken:(NSString *)accessToken tokenSecret:(NSString *)tokenSecret { - return [self URLRequestForPath:path - urlMethod:@"POST" - parameters:parameters - scheme:scheme - host:host - consumerKey:consumerKey - consumerSecret:consumerSecret - accessToken:accessToken + return [self URLRequestForPath:path + HTTPMethod:@"GET" + parameters:parameters + scheme:scheme + host:host + consumerKey:consumerKey + consumerSecret:consumerSecret + accessToken:accessToken tokenSecret:tokenSecret]; - } - + (NSURLRequest *)URLRequestForPath:(NSString *)path - PUTParameters:(NSDictionary *)parameters + POSTParameters:(NSDictionary *)parameters host:(NSString *)host consumerKey:(NSString *)consumerKey consumerSecret:(NSString *)consumerSecret accessToken:(NSString *)accessToken - tokenSecret:(NSString *)tokenSecret { - - return [self URLRequestForPath:path - PUTParameters:parameters - scheme:@"HTTPS" - host:host - consumerKey:consumerKey - consumerSecret:consumerSecret - accessToken:accessToken + tokenSecret:(NSString *)tokenSecret +{ + return [self URLRequestForPath:path + HTTPMethod:@"POST" + parameters:parameters + scheme:@"https" + host:host + consumerKey:consumerKey + consumerSecret:consumerSecret + accessToken:accessToken tokenSecret:tokenSecret]; } - + (NSURLRequest *)URLRequestForPath:(NSString *)path - PUTParameters:(NSDictionary *)parameters + POSTParameters:(NSDictionary *)parameters scheme:(NSString *)scheme host:(NSString *)host consumerKey:(NSString *)consumerKey @@ -350,57 +333,16 @@ + (NSURLRequest *)URLRequestForPath:(NSString *)path accessToken:(NSString *)accessToken tokenSecret:(NSString *)tokenSecret { - - return [self URLRequestForPath:path - urlMethod:@"PUT" - parameters:parameters - scheme:scheme - host:host - consumerKey:consumerKey - consumerSecret:consumerSecret - accessToken:accessToken + return [self URLRequestForPath:path + HTTPMethod:@"POST" + parameters:parameters + scheme:scheme + host:host + consumerKey:consumerKey + consumerSecret:consumerSecret + accessToken:accessToken tokenSecret:tokenSecret]; -} - - -+ (NSURLRequest *)URLRequestForPath:(NSString *)path - urlMethod:(NSString *)urlMethod - parameters:(NSDictionary *)parameters - scheme:(NSString *)scheme - host:(NSString *)host - consumerKey:(NSString *)consumerKey - consumerSecret:(NSString *)consumerSecret - accessToken:(NSString *)accessToken - tokenSecret:(NSString *)tokenSecret { - - // check parameters - if (host == nil || path == nil) { return nil; } - - // create object - GCOAuth *oauth = [[GCOAuth alloc] initWithConsumerKey:consumerKey - consumerSecret:consumerSecret - accessToken:accessToken - tokenSecret:tokenSecret]; - oauth.HTTPMethod = urlMethod; - oauth.requestParameters = parameters; - NSURL *URL = [[NSURL alloc] initWithScheme:scheme host:host path:path]; - oauth.URL = URL; - [URL release]; - - // create request - NSMutableURLRequest *request = [oauth request]; - if ([oauth.requestParameters count]) { - NSString *query = [GCOAuth queryStringFromParameters:oauth.requestParameters]; - NSData *data = [query dataUsingEncoding:NSUTF8StringEncoding]; - NSString *length = [NSString stringWithFormat:@"%lu", (unsigned long)[data length]]; - [request setHTTPBody:data]; - [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; - [request setValue:length forHTTPHeaderField:@"Content-Length"]; - } - // return - [oauth release]; - return request; } @end