diff --git a/Code/CoreData/NSManagedObject+ActiveRecord.h b/Code/CoreData/NSManagedObject+ActiveRecord.h index c4603ed2..1d05f63e 100644 --- a/Code/CoreData/NSManagedObject+ActiveRecord.h +++ b/Code/CoreData/NSManagedObject+ActiveRecord.h @@ -28,13 +28,13 @@ @interface NSManagedObject (ActiveRecord) /** - * The NSEntityDescription for the Subclass - * defaults to the subclass className, may be overridden + * The NSEntityDescription for the Subclass + * defaults to the subclass className, may be overridden */ + (NSEntityDescription*)entity; /** - * Returns an initialized NSFetchRequest for the entity, with no predicate + * Returns an initialized NSFetchRequest for the entity, with no predicate */ + (NSFetchRequest*)fetchRequest; @@ -94,7 +94,7 @@ + (NSUInteger)count DEPRECATED_ATTRIBUTE; /** - * Creates a new managed object and inserts it into the managedObjectContext. + * Creates a new managed object and inserts it into the managedObjectContext. */ + (id)object; diff --git a/Code/CoreData/NSManagedObject+ActiveRecord.m b/Code/CoreData/NSManagedObject+ActiveRecord.m index aea45b82..f8de2ca6 100644 --- a/Code/CoreData/NSManagedObject+ActiveRecord.m +++ b/Code/CoreData/NSManagedObject+ActiveRecord.m @@ -52,84 +52,84 @@ RK_FIX_CATEGORY_BUG(NSManagedObject_ActiveRecord) #pragma mark - RKManagedObject methods + (NSEntityDescription*)entity { - NSString* className = [NSString stringWithCString:class_getName([self class]) encoding:NSASCIIStringEncoding]; - return [NSEntityDescription entityForName:className inManagedObjectContext:[NSManagedObjectContext contextForCurrentThread]]; + NSString* className = [NSString stringWithCString:class_getName([self class]) encoding:NSASCIIStringEncoding]; + return [NSEntityDescription entityForName:className inManagedObjectContext:[NSManagedObjectContext contextForCurrentThread]]; } + (NSFetchRequest*)fetchRequest { - NSFetchRequest *fetchRequest = [[[NSFetchRequest alloc] init] autorelease]; - NSEntityDescription *entity = [self entity]; - [fetchRequest setEntity:entity]; - return 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]; - if (objects == nil) { - RKLogError(@"Error: %@", [error localizedDescription]); - } - return objects; + 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 objectCount = [[NSManagedObjectContext contextForCurrentThread] countForFetchRequest:fetchRequest error:&error]; - if (objectCount == NSNotFound) { - RKLogError(@"Error: %@", [error localizedDescription]); - } - return objectCount; + NSError* error = nil; + NSUInteger objectCount = [[NSManagedObjectContext contextForCurrentThread] countForFetchRequest:fetchRequest error:&error]; + if (objectCount == NSNotFound) { + RKLogError(@"Error: %@", [error localizedDescription]); + } + return objectCount; } + (NSArray*)objectsWithFetchRequests:(NSArray*)fetchRequests { - NSMutableArray* mutableObjectArray = [[NSMutableArray alloc] init]; - for (NSFetchRequest* fetchRequest in fetchRequests) { - [mutableObjectArray addObjectsFromArray:[self objectsWithFetchRequest:fetchRequest]]; - } - NSArray* objects = [NSArray arrayWithArray:mutableObjectArray]; - [mutableObjectArray release]; - return objects; + NSMutableArray* mutableObjectArray = [[NSMutableArray alloc] init]; + for (NSFetchRequest* fetchRequest in fetchRequests) { + [mutableObjectArray addObjectsFromArray:[self objectsWithFetchRequest:fetchRequest]]; + } + NSArray* objects = [NSArray arrayWithArray:mutableObjectArray]; + [mutableObjectArray release]; + return objects; } + (id)objectWithFetchRequest:(NSFetchRequest*)fetchRequest { - [fetchRequest setFetchLimit:1]; - NSArray* objects = [self objectsWithFetchRequest:fetchRequest]; - if ([objects count] == 0) { - return nil; - } else { - return [objects objectAtIndex:0]; - } + [fetchRequest setFetchLimit:1]; + NSArray* objects = [self objectsWithFetchRequest:fetchRequest]; + if ([objects count] == 0) { + return nil; + } else { + return [objects objectAtIndex:0]; + } } + (NSArray*)objectsWithPredicate:(NSPredicate*)predicate { - NSFetchRequest* fetchRequest = [self fetchRequest]; - [fetchRequest setPredicate:predicate]; - return [self objectsWithFetchRequest:fetchRequest]; + NSFetchRequest* fetchRequest = [self fetchRequest]; + [fetchRequest setPredicate:predicate]; + return [self objectsWithFetchRequest:fetchRequest]; } + (id)objectWithPredicate:(NSPredicate*)predicate { - NSFetchRequest* fetchRequest = [self fetchRequest]; - [fetchRequest setPredicate:predicate]; - return [self objectWithFetchRequest:fetchRequest]; + NSFetchRequest* fetchRequest = [self fetchRequest]; + [fetchRequest setPredicate:predicate]; + return [self objectWithFetchRequest:fetchRequest]; } + (NSArray*)allObjects { - return [self objectsWithPredicate:nil]; + return [self objectsWithPredicate:nil]; } + (NSUInteger)count:(NSError**)error { - NSFetchRequest* fetchRequest = [self fetchRequest]; - return [[NSManagedObjectContext contextForCurrentThread] countForFetchRequest:fetchRequest error:error]; + NSFetchRequest* fetchRequest = [self fetchRequest]; + return [[NSManagedObjectContext contextForCurrentThread] countForFetchRequest:fetchRequest error:error]; } + (NSUInteger)count { - NSError *error = nil; - return [self count:&error]; + NSError *error = nil; + return [self count:&error]; } + (id)object { - id object = [[self alloc] initWithEntity:[self entity] insertIntoManagedObjectContext:[NSManagedObjectContext contextForCurrentThread]]; - return [object autorelease]; + id object = [[self alloc] initWithEntity:[self entity] insertIntoManagedObjectContext:[NSManagedObjectContext contextForCurrentThread]]; + return [object autorelease]; } - (BOOL)isNew { @@ -160,91 +160,91 @@ RK_FIX_CATEGORY_BUG(NSManagedObject_ActiveRecord) + (void)setDefaultBatchSize:(NSUInteger)newBatchSize { - @synchronized(defaultBatchSize) - { - defaultBatchSize = [NSNumber numberWithUnsignedInteger:newBatchSize]; - } + @synchronized(defaultBatchSize) + { + defaultBatchSize = [NSNumber numberWithUnsignedInteger:newBatchSize]; + } } + (NSInteger)defaultBatchSize { - if (defaultBatchSize == nil) - { - [self setDefaultBatchSize:kActiveRecordDefaultBatchSize]; - } - return [defaultBatchSize integerValue]; + if (defaultBatchSize == nil) + { + [self setDefaultBatchSize:kActiveRecordDefaultBatchSize]; + } + return [defaultBatchSize integerValue]; } + (void)handleErrors:(NSError *)error { - if (error) - { - NSDictionary *userInfo = [error userInfo]; - for (NSArray *detailedError in [userInfo allValues]) - { - if ([detailedError isKindOfClass:[NSArray class]]) - { - for (NSError *e in detailedError) - { - if ([e respondsToSelector:@selector(userInfo)]) - { - RKLogError(@"Error Details: %@", [e userInfo]); - } - else - { - RKLogError(@"Error Details: %@", e); - } - } - } - else - { - RKLogError(@"Error: %@", detailedError); - } - } - RKLogError(@"Error Domain: %@", [error domain]); - RKLogError(@"Recovery Suggestion: %@", [error localizedRecoverySuggestion]); - } + if (error) + { + NSDictionary *userInfo = [error userInfo]; + for (NSArray *detailedError in [userInfo allValues]) + { + if ([detailedError isKindOfClass:[NSArray class]]) + { + for (NSError *e in detailedError) + { + if ([e respondsToSelector:@selector(userInfo)]) + { + RKLogError(@"Error Details: %@", [e userInfo]); + } + else + { + RKLogError(@"Error Details: %@", e); + } + } + } + else + { + RKLogError(@"Error: %@", detailedError); + } + } + RKLogError(@"Error Domain: %@", [error domain]); + RKLogError(@"Recovery Suggestion: %@", [error localizedRecoverySuggestion]); + } } + (NSArray *)executeFetchRequest:(NSFetchRequest *)request inContext:(NSManagedObjectContext *)context { - NSError *error = nil; + NSError *error = nil; - NSArray *results = [context executeFetchRequest:request error:&error]; - [self handleErrors:error]; - return results; + NSArray *results = [context executeFetchRequest:request error:&error]; + [self handleErrors:error]; + return results; } + (NSArray *)executeFetchRequest:(NSFetchRequest *)request { - return [self executeFetchRequest:request inContext:[self currentContext]]; + return [self executeFetchRequest:request inContext:[self currentContext]]; } + (id)executeFetchRequestAndReturnFirstObject:(NSFetchRequest *)request inContext:(NSManagedObjectContext *)context { - [request setFetchLimit:1]; + [request setFetchLimit:1]; - NSArray *results = [self executeFetchRequest:request inContext:context]; - if ([results count] == 0) - { - return nil; - } - return [results objectAtIndex:0]; + NSArray *results = [self executeFetchRequest:request inContext:context]; + if ([results count] == 0) + { + return nil; + } + return [results objectAtIndex:0]; } + (id)executeFetchRequestAndReturnFirstObject:(NSFetchRequest *)request { - return [self executeFetchRequestAndReturnFirstObject:request inContext:[self currentContext]]; + return [self executeFetchRequestAndReturnFirstObject:request inContext:[self currentContext]]; } #if TARGET_OS_IPHONE + (void)performFetch:(NSFetchedResultsController *)controller { - NSError *error = nil; - if (![controller performFetch:&error]) - { - [self handleErrors:error]; - } + NSError *error = nil; + if (![controller performFetch:&error]) + { + [self handleErrors:error]; + } } #endif @@ -256,84 +256,84 @@ RK_FIX_CATEGORY_BUG(NSManagedObject_ActiveRecord) + (NSEntityDescription *)entityDescription { - return [self entityDescriptionInContext:[self currentContext]]; + return [self entityDescriptionInContext:[self currentContext]]; } + (NSArray *)propertiesNamed:(NSArray *)properties { - NSEntityDescription *description = [self entityDescription]; - NSMutableArray *propertiesWanted = [NSMutableArray array]; + NSEntityDescription *description = [self entityDescription]; + NSMutableArray *propertiesWanted = [NSMutableArray array]; - if (properties) - { - NSDictionary *propDict = [description propertiesByName]; + if (properties) + { + NSDictionary *propDict = [description propertiesByName]; - for (NSString *propertyName in properties) - { - NSPropertyDescription *property = [propDict objectForKey:propertyName]; - if (property) - { - [propertiesWanted addObject:property]; - } - else - { - RKLogError(@"Property '%@' not found in %@ properties for %@", propertyName, [propDict count], NSStringFromClass(self)); - } - } - } - return propertiesWanted; + for (NSString *propertyName in properties) + { + NSPropertyDescription *property = [propDict objectForKey:propertyName]; + if (property) + { + [propertiesWanted addObject:property]; + } + else + { + RKLogError(@"Property '%@' not found in %@ properties for %@", propertyName, [propDict count], NSStringFromClass(self)); + } + } + } + return propertiesWanted; } + (NSArray *)sortAscending:(BOOL)ascending attributes:(id)attributesToSortBy, ... { - NSMutableArray *attributes = [NSMutableArray array]; + NSMutableArray *attributes = [NSMutableArray array]; - if ([attributesToSortBy isKindOfClass:[NSArray class]]) - { - id attributeName; - va_list variadicArguments; - va_start(variadicArguments, attributesToSortBy); - while ((attributeName = va_arg(variadicArguments, id))!= nil) - { - NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:attributeName ascending:ascending]; - [attributes addObject:sortDescriptor]; - [sortDescriptor release]; - } - va_end(variadicArguments); + if ([attributesToSortBy isKindOfClass:[NSArray class]]) + { + id attributeName; + va_list variadicArguments; + va_start(variadicArguments, attributesToSortBy); + while ((attributeName = va_arg(variadicArguments, id))!= nil) + { + NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:attributeName ascending:ascending]; + [attributes addObject:sortDescriptor]; + [sortDescriptor release]; + } + va_end(variadicArguments); - } - else if ([attributesToSortBy isKindOfClass:[NSString class]]) - { - va_list variadicArguments; - va_start(variadicArguments, attributesToSortBy); - [attributes addObject:[[[NSSortDescriptor alloc] initWithKey:attributesToSortBy ascending:ascending] autorelease] ]; - va_end(variadicArguments); - } + } + else if ([attributesToSortBy isKindOfClass:[NSString class]]) + { + va_list variadicArguments; + va_start(variadicArguments, attributesToSortBy); + [attributes addObject:[[[NSSortDescriptor alloc] initWithKey:attributesToSortBy ascending:ascending] autorelease] ]; + va_end(variadicArguments); + } - return attributes; + return attributes; } + (NSArray *)ascendingSortDescriptors:(id)attributesToSortBy, ... { - return [self sortAscending:YES attributes:attributesToSortBy]; + return [self sortAscending:YES attributes:attributesToSortBy]; } + (NSArray *)descendingSortDescriptors:(id)attributesToSortyBy, ... { - return [self sortAscending:NO attributes:attributesToSortyBy]; + return [self sortAscending:NO attributes:attributesToSortyBy]; } + (NSFetchRequest *)createFetchRequestInContext:(NSManagedObjectContext *)context { - NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease]; - [request setEntity:[self entityDescriptionInContext:context]]; + NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease]; + [request setEntity:[self entityDescriptionInContext:context]]; - return request; + return request; } + (NSFetchRequest *)createFetchRequest { - return [self createFetchRequestInContext:[self currentContext]]; + return [self createFetchRequestInContext:[self currentContext]]; } #pragma mark - @@ -341,34 +341,34 @@ RK_FIX_CATEGORY_BUG(NSManagedObject_ActiveRecord) + (NSNumber *)numberOfEntitiesWithContext:(NSManagedObjectContext *)context { - NSError *error = nil; - NSUInteger count = [context countForFetchRequest:[self createFetchRequestInContext:context] error:&error]; - [self handleErrors:error]; + NSError *error = nil; + NSUInteger count = [context countForFetchRequest:[self createFetchRequestInContext:context] error:&error]; + [self handleErrors:error]; - return [NSNumber numberWithUnsignedInteger:count]; + return [NSNumber numberWithUnsignedInteger:count]; } + (NSNumber *)numberOfEntities { - return [self numberOfEntitiesWithContext:[self currentContext]]; + return [self numberOfEntitiesWithContext:[self currentContext]]; } + (NSNumber *)numberOfEntitiesWithPredicate:(NSPredicate *)searchTerm inContext:(NSManagedObjectContext *)context { - NSError *error = nil; - NSFetchRequest *request = [self createFetchRequestInContext:context]; - [request setPredicate:searchTerm]; + NSError *error = nil; + NSFetchRequest *request = [self createFetchRequestInContext:context]; + [request setPredicate:searchTerm]; - NSUInteger count = [context countForFetchRequest:request error:&error]; - [self handleErrors:error]; + NSUInteger count = [context countForFetchRequest:request error:&error]; + [self handleErrors:error]; - return [NSNumber numberWithUnsignedInteger:count]; + return [NSNumber numberWithUnsignedInteger:count]; } + (NSNumber *)numberOfEntitiesWithPredicate:(NSPredicate *)searchTerm; { - return [self numberOfEntitiesWithPredicate:searchTerm - inContext:[self currentContext]]; + return [self numberOfEntitiesWithPredicate:searchTerm + inContext:[self currentContext]]; } + (BOOL)hasAtLeastOneEntityInContext:(NSManagedObjectContext *)context @@ -385,12 +385,12 @@ RK_FIX_CATEGORY_BUG(NSManagedObject_ActiveRecord) #pragma mark Reqest Helpers + (NSFetchRequest *)requestAll { - return [self createFetchRequestInContext:[self currentContext]]; + return [self createFetchRequestInContext:[self currentContext]]; } + (NSFetchRequest *)requestAllInContext:(NSManagedObjectContext *)context { - return [self createFetchRequestInContext:context]; + return [self createFetchRequestInContext:context]; } + (NSFetchRequest *)requestAllWhere:(NSString *)property isEqualTo:(id)value inContext:(NSManagedObjectContext *)context @@ -435,45 +435,45 @@ RK_FIX_CATEGORY_BUG(NSManagedObject_ActiveRecord) + (NSFetchRequest *)requestAllSortedBy:(NSString *)sortTerm ascending:(BOOL)ascending inContext:(NSManagedObjectContext *)context { - NSFetchRequest *request = [self requestAllInContext:context]; + NSFetchRequest *request = [self requestAllInContext:context]; - NSSortDescriptor *sortBy = [[NSSortDescriptor alloc] initWithKey:sortTerm ascending:ascending]; - [request setSortDescriptors:[NSArray arrayWithObject:sortBy]]; - [sortBy release]; + NSSortDescriptor *sortBy = [[NSSortDescriptor alloc] initWithKey:sortTerm ascending:ascending]; + [request setSortDescriptors:[NSArray arrayWithObject:sortBy]]; + [sortBy release]; - return request; + return request; } + (NSFetchRequest *)requestAllSortedBy:(NSString *)sortTerm ascending:(BOOL)ascending { - return [self requestAllSortedBy:sortTerm - ascending:ascending - inContext:[self currentContext]]; + return [self requestAllSortedBy:sortTerm + ascending:ascending + inContext:[self currentContext]]; } + (NSFetchRequest *)requestAllSortedBy:(NSString *)sortTerm ascending:(BOOL)ascending withPredicate:(NSPredicate *)searchTerm inContext:(NSManagedObjectContext *)context { - NSFetchRequest *request = [self requestAllInContext:context]; - [request setPredicate:searchTerm]; - [request setIncludesSubentities:NO]; - [request setFetchBatchSize:[self defaultBatchSize]]; + NSFetchRequest *request = [self requestAllInContext:context]; + [request setPredicate:searchTerm]; + [request setIncludesSubentities:NO]; + [request setFetchBatchSize:[self defaultBatchSize]]; - if (sortTerm != nil){ - NSSortDescriptor *sortBy = [[NSSortDescriptor alloc] initWithKey:sortTerm ascending:ascending]; - [request setSortDescriptors:[NSArray arrayWithObject:sortBy]]; - [sortBy release]; - } + if (sortTerm != nil){ + NSSortDescriptor *sortBy = [[NSSortDescriptor alloc] initWithKey:sortTerm ascending:ascending]; + [request setSortDescriptors:[NSArray arrayWithObject:sortBy]]; + [sortBy release]; + } - return request; + return request; } + (NSFetchRequest *)requestAllSortedBy:(NSString *)sortTerm ascending:(BOOL)ascending withPredicate:(NSPredicate *)searchTerm; { - NSFetchRequest *request = [self requestAllSortedBy:sortTerm - ascending:ascending - withPredicate:searchTerm - inContext:[self currentContext]]; - return request; + NSFetchRequest *request = [self requestAllSortedBy:sortTerm + ascending:ascending + withPredicate:searchTerm + inContext:[self currentContext]]; + return request; } @@ -482,44 +482,44 @@ RK_FIX_CATEGORY_BUG(NSManagedObject_ActiveRecord) + (NSArray *)findAllInContext:(NSManagedObjectContext *)context { - return [self executeFetchRequest:[self requestAllInContext:context] inContext:context]; + return [self executeFetchRequest:[self requestAllInContext:context] inContext:context]; } + (NSArray *)findAll { - return [self findAllInContext:[self currentContext]]; + return [self findAllInContext:[self currentContext]]; } + (NSArray *)findAllSortedBy:(NSString *)sortTerm ascending:(BOOL)ascending inContext:(NSManagedObjectContext *)context { - NSFetchRequest *request = [self requestAllSortedBy:sortTerm ascending:ascending inContext:context]; + NSFetchRequest *request = [self requestAllSortedBy:sortTerm ascending:ascending inContext:context]; - return [self executeFetchRequest:request inContext:context]; + return [self executeFetchRequest:request inContext:context]; } + (NSArray *)findAllSortedBy:(NSString *)sortTerm ascending:(BOOL)ascending { - return [self findAllSortedBy:sortTerm - ascending:ascending - inContext:[self currentContext]]; + return [self findAllSortedBy:sortTerm + ascending:ascending + inContext:[self currentContext]]; } + (NSArray *)findAllSortedBy:(NSString *)sortTerm ascending:(BOOL)ascending withPredicate:(NSPredicate *)searchTerm inContext:(NSManagedObjectContext *)context { - NSFetchRequest *request = [self requestAllSortedBy:sortTerm - ascending:ascending - withPredicate:searchTerm - inContext:context]; + NSFetchRequest *request = [self requestAllSortedBy:sortTerm + ascending:ascending + withPredicate:searchTerm + inContext:context]; - return [self executeFetchRequest:request inContext:context]; + return [self executeFetchRequest:request inContext:context]; } + (NSArray *)findAllSortedBy:(NSString *)sortTerm ascending:(BOOL)ascending withPredicate:(NSPredicate *)searchTerm { - return [self findAllSortedBy:sortTerm - ascending:ascending - withPredicate:searchTerm - inContext:[self currentContext]]; + return [self findAllSortedBy:sortTerm + ascending:ascending + withPredicate:searchTerm + inContext:[self currentContext]]; } #pragma mark - @@ -529,73 +529,73 @@ RK_FIX_CATEGORY_BUG(NSManagedObject_ActiveRecord) + (NSFetchedResultsController *)fetchRequestAllGroupedBy:(NSString *)group withPredicate:(NSPredicate *)searchTerm sortedBy:(NSString *)sortTerm ascending:(BOOL)ascending inContext:(NSManagedObjectContext *)context { - NSString *cacheName = nil; + NSString *cacheName = nil; #ifdef STORE_USE_CACHE - cacheName = [NSString stringWithFormat:@"ActiveRecord-Cache-%@", NSStringFromClass(self)]; + cacheName = [NSString stringWithFormat:@"ActiveRecord-Cache-%@", NSStringFromClass(self)]; #endif - NSFetchRequest *request = [self requestAllSortedBy:sortTerm - ascending:ascending - withPredicate:searchTerm - inContext:context]; + NSFetchRequest *request = [self requestAllSortedBy:sortTerm + ascending:ascending + withPredicate:searchTerm + inContext:context]; - NSFetchedResultsController *controller = [[NSFetchedResultsController alloc] initWithFetchRequest:request - managedObjectContext:context - sectionNameKeyPath:group - cacheName:cacheName]; - return [controller autorelease]; + NSFetchedResultsController *controller = [[NSFetchedResultsController alloc] initWithFetchRequest:request + managedObjectContext:context + sectionNameKeyPath:group + cacheName:cacheName]; + return [controller autorelease]; } + (NSFetchedResultsController *)fetchRequestAllGroupedBy:(NSString *)group withPredicate:(NSPredicate *)searchTerm sortedBy:(NSString *)sortTerm ascending:(BOOL)ascending { - return [self fetchRequestAllGroupedBy:group - withPredicate:searchTerm - sortedBy:sortTerm - ascending:ascending - inContext:[self currentContext]]; + return [self fetchRequestAllGroupedBy:group + withPredicate:searchTerm + sortedBy:sortTerm + ascending:ascending + inContext:[self currentContext]]; } + (NSFetchedResultsController *)fetchAllSortedBy:(NSString *)sortTerm ascending:(BOOL)ascending withPredicate:(NSPredicate *)searchTerm groupBy:(NSString *)groupingKeyPath inContext:(NSManagedObjectContext *)context { - NSFetchedResultsController *controller = [self fetchRequestAllGroupedBy:groupingKeyPath - withPredicate:searchTerm - sortedBy:sortTerm - ascending:ascending - inContext:context]; + NSFetchedResultsController *controller = [self fetchRequestAllGroupedBy:groupingKeyPath + withPredicate:searchTerm + sortedBy:sortTerm + ascending:ascending + inContext:context]; - [self performFetch:controller]; - return controller; + [self performFetch:controller]; + return controller; } + (NSFetchedResultsController *)fetchAllSortedBy:(NSString *)sortTerm ascending:(BOOL)ascending withPredicate:(NSPredicate *)searchTerm groupBy:(NSString *)groupingKeyPath { - return [self fetchAllSortedBy:sortTerm - ascending:ascending - withPredicate:searchTerm - groupBy:groupingKeyPath - inContext:[self currentContext]]; + return [self fetchAllSortedBy:sortTerm + ascending:ascending + withPredicate:searchTerm + groupBy:groupingKeyPath + inContext:[self currentContext]]; } + (NSFetchedResultsController *)fetchRequest:(NSFetchRequest *)request groupedBy:(NSString *)group inContext:(NSManagedObjectContext *)context { - NSString *cacheName = nil; + NSString *cacheName = nil; #ifdef STORE_USE_CACHE - cacheName = [NSString stringWithFormat:@"ActiveRecord-Cache-%@", NSStringFromClass([self class])]; + cacheName = [NSString stringWithFormat:@"ActiveRecord-Cache-%@", NSStringFromClass([self class])]; #endif - NSFetchedResultsController *controller = + NSFetchedResultsController *controller = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:context sectionNameKeyPath:group cacheName:cacheName]; [self performFetch:controller]; - return [controller autorelease]; + return [controller autorelease]; } + (NSFetchedResultsController *)fetchRequest:(NSFetchRequest *)request groupedBy:(NSString *)group { - return [self fetchRequest:request - groupedBy:group - inContext:[self currentContext]]; + return [self fetchRequest:request + groupedBy:group + inContext:[self currentContext]]; } #endif @@ -603,43 +603,43 @@ RK_FIX_CATEGORY_BUG(NSManagedObject_ActiveRecord) + (NSArray *)findAllWithPredicate:(NSPredicate *)searchTerm inContext:(NSManagedObjectContext *)context { - NSFetchRequest *request = [self createFetchRequestInContext:context]; - [request setPredicate:searchTerm]; + NSFetchRequest *request = [self createFetchRequestInContext:context]; + [request setPredicate:searchTerm]; - return [self executeFetchRequest:request - inContext:context]; + return [self executeFetchRequest:request + inContext:context]; } + (NSArray *)findAllWithPredicate:(NSPredicate *)searchTerm { - return [self findAllWithPredicate:searchTerm - inContext:[self currentContext]]; + return [self findAllWithPredicate:searchTerm + inContext:[self currentContext]]; } + (id)findFirstInContext:(NSManagedObjectContext *)context { - NSFetchRequest *request = [self createFetchRequestInContext:context]; + NSFetchRequest *request = [self createFetchRequestInContext:context]; - return [self executeFetchRequestAndReturnFirstObject:request inContext:context]; + return [self executeFetchRequestAndReturnFirstObject:request inContext:context]; } + (id)findFirst { - return [self findFirstInContext:[self currentContext]]; + return [self findFirstInContext:[self currentContext]]; } + (id)findFirstByAttribute:(NSString *)attribute withValue:(id)searchValue inContext:(NSManagedObjectContext *)context { - NSFetchRequest *request = [self requestFirstByAttribute:attribute withValue:searchValue inContext:context]; + NSFetchRequest *request = [self requestFirstByAttribute:attribute withValue:searchValue inContext:context]; - return [self executeFetchRequestAndReturnFirstObject:request inContext:context]; + return [self executeFetchRequestAndReturnFirstObject:request inContext:context]; } + (id)findFirstByAttribute:(NSString *)attribute withValue:(id)searchValue { - return [self findFirstByAttribute:attribute - withValue:searchValue - inContext:[self currentContext]]; + return [self findFirstByAttribute:attribute + withValue:searchValue + inContext:[self currentContext]]; } + (id)findFirstWithPredicate:(NSPredicate *)searchTerm inContext:(NSManagedObjectContext *)context @@ -656,85 +656,85 @@ RK_FIX_CATEGORY_BUG(NSManagedObject_ActiveRecord) + (id)findFirstWithPredicate:(NSPredicate *)searchterm sortedBy:(NSString *)property ascending:(BOOL)ascending inContext:(NSManagedObjectContext *)context { - NSFetchRequest *request = [self requestAllSortedBy:property ascending:ascending withPredicate:searchterm inContext:context]; + NSFetchRequest *request = [self requestAllSortedBy:property ascending:ascending withPredicate:searchterm inContext:context]; - return [self executeFetchRequestAndReturnFirstObject:request inContext:context]; + return [self executeFetchRequestAndReturnFirstObject:request inContext:context]; } + (id)findFirstWithPredicate:(NSPredicate *)searchterm sortedBy:(NSString *)property ascending:(BOOL)ascending { - return [self findFirstWithPredicate:searchterm - sortedBy:property - ascending:ascending - inContext:[self currentContext]]; + return [self findFirstWithPredicate:searchterm + sortedBy:property + ascending:ascending + inContext:[self currentContext]]; } + (id)findFirstWithPredicate:(NSPredicate *)searchTerm andRetrieveAttributes:(NSArray *)attributes inContext:(NSManagedObjectContext *)context { - NSFetchRequest *request = [self createFetchRequestInContext:context]; - [request setPredicate:searchTerm]; + NSFetchRequest *request = [self createFetchRequestInContext:context]; + [request setPredicate:searchTerm]; - return [self executeFetchRequestAndReturnFirstObject:request inContext:context]; + return [self executeFetchRequestAndReturnFirstObject:request inContext:context]; } + (id)findFirstWithPredicate:(NSPredicate *)searchTerm andRetrieveAttributes:(NSArray *)attributes { - return [self findFirstWithPredicate:searchTerm - andRetrieveAttributes:attributes - inContext:[self currentContext]]; + return [self findFirstWithPredicate:searchTerm + andRetrieveAttributes:attributes + inContext:[self currentContext]]; } + (id)findFirstWithPredicate:(NSPredicate *)searchTerm sortedBy:(NSString *)sortBy ascending:(BOOL)ascending inContext:(NSManagedObjectContext *)context andRetrieveAttributes:(id)attributes, ... { - NSFetchRequest *request = [self requestAllSortedBy:sortBy - ascending:ascending - withPredicate:searchTerm - inContext:context]; + NSFetchRequest *request = [self requestAllSortedBy:sortBy + ascending:ascending + withPredicate:searchTerm + inContext:context]; - return [self executeFetchRequestAndReturnFirstObject:request inContext:context]; + return [self executeFetchRequestAndReturnFirstObject:request inContext:context]; } + (id)findFirstWithPredicate:(NSPredicate *)searchTerm sortedBy:(NSString *)sortBy ascending:(BOOL)ascending andRetrieveAttributes:(id)attributes, ... { - return [self findFirstWithPredicate:searchTerm - sortedBy:sortBy - ascending:ascending + return [self findFirstWithPredicate:searchTerm + sortedBy:sortBy + ascending:ascending inContext:[self currentContext] - andRetrieveAttributes:attributes]; + andRetrieveAttributes:attributes]; } + (NSArray *)findByAttribute:(NSString *)attribute withValue:(id)searchValue inContext:(NSManagedObjectContext *)context { - NSFetchRequest *request = [self createFetchRequestInContext:context]; + NSFetchRequest *request = [self createFetchRequestInContext:context]; - [request setPredicate:[NSPredicate predicateWithFormat:@"%K = %@", attribute, searchValue]]; + [request setPredicate:[NSPredicate predicateWithFormat:@"%K = %@", attribute, searchValue]]; - return [self executeFetchRequest:request inContext:context]; + return [self executeFetchRequest:request inContext:context]; } + (NSArray *)findByAttribute:(NSString *)attribute withValue:(id)searchValue { - return [self findByAttribute:attribute - withValue:searchValue - inContext:[self currentContext]]; + return [self findByAttribute:attribute + withValue:searchValue + inContext:[self currentContext]]; } + (NSArray *)findByAttribute:(NSString *)attribute withValue:(id)searchValue andOrderBy:(NSString *)sortTerm ascending:(BOOL)ascending inContext:(NSManagedObjectContext *)context { - NSPredicate *searchTerm = [NSPredicate predicateWithFormat:@"%K = %@", attribute, searchValue]; - NSFetchRequest *request = [self requestAllSortedBy:sortTerm ascending:ascending withPredicate:searchTerm inContext:context]; + NSPredicate *searchTerm = [NSPredicate predicateWithFormat:@"%K = %@", attribute, searchValue]; + NSFetchRequest *request = [self requestAllSortedBy:sortTerm ascending:ascending withPredicate:searchTerm inContext:context]; - return [self executeFetchRequest:request]; + return [self executeFetchRequest:request]; } + (NSArray *)findByAttribute:(NSString *)attribute withValue:(id)searchValue andOrderBy:(NSString *)sortTerm ascending:(BOOL)ascending { - return [self findByAttribute:attribute - withValue:searchValue - andOrderBy:sortTerm - ascending:ascending - inContext:[self currentContext]]; + return [self findByAttribute:attribute + withValue:searchValue + andOrderBy:sortTerm + ascending:ascending + inContext:[self currentContext]]; } + (id)createInContext:(NSManagedObjectContext *)context @@ -745,21 +745,21 @@ RK_FIX_CATEGORY_BUG(NSManagedObject_ActiveRecord) + (id)createEntity { - NSManagedObject *newEntity = [self createInContext:[self currentContext]]; + NSManagedObject *newEntity = [self createInContext:[self currentContext]]; - return newEntity; + return newEntity; } - (BOOL)deleteInContext:(NSManagedObjectContext *)context { - [context deleteObject:self]; - return YES; + [context deleteObject:self]; + return YES; } - (BOOL)deleteEntity { - [self deleteInContext:[[self class] currentContext]]; - return YES; + [self deleteInContext:[[self class] currentContext]]; + return YES; } + (BOOL)truncateAllInContext:(NSManagedObjectContext *)context @@ -780,25 +780,25 @@ RK_FIX_CATEGORY_BUG(NSManagedObject_ActiveRecord) + (NSNumber *)maxValueFor:(NSString *)property { - NSManagedObject *obj = [[self class] findFirstByAttribute:property - withValue:[NSString stringWithFormat:@"max(%@)", property]]; + NSManagedObject *obj = [[self class] findFirstByAttribute:property + withValue:[NSString stringWithFormat:@"max(%@)", property]]; - return [obj valueForKey:property]; + return [obj valueForKey:property]; } + (id)objectWithMinValueFor:(NSString *)property inContext:(NSManagedObjectContext *)context { - NSFetchRequest *request = [[self class] createFetchRequestInContext:context]; + NSFetchRequest *request = [[self class] createFetchRequestInContext:context]; - NSPredicate *searchFor = [NSPredicate predicateWithFormat:@"SELF = %@ AND %K = min(%@)", self, property, property]; - [request setPredicate:searchFor]; + NSPredicate *searchFor = [NSPredicate predicateWithFormat:@"SELF = %@ AND %K = min(%@)", self, property, property]; + [request setPredicate:searchFor]; - return [[self class] executeFetchRequestAndReturnFirstObject:request inContext:context]; + return [[self class] executeFetchRequestAndReturnFirstObject:request inContext:context]; } + (id)objectWithMinValueFor:(NSString *)property { - return [[self class] objectWithMinValueFor:property inContext:[self currentContext]]; + return [[self class] objectWithMinValueFor:property inContext:[self currentContext]]; } @end diff --git a/Code/CoreData/RKManagedObjectMapping.m b/Code/CoreData/RKManagedObjectMapping.m index 9ca88cb8..16c92bce 100644 --- a/Code/CoreData/RKManagedObjectMapping.m +++ b/Code/CoreData/RKManagedObjectMapping.m @@ -104,7 +104,7 @@ va_list args; va_start(args, firstRelationshipName); for (NSString* relationshipName = firstRelationshipName; relationshipName != nil; relationshipName = va_arg(args, NSString*)) { - NSString* primaryKeyAttribute = 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... diff --git a/Code/CoreData/RKManagedObjectSearchEngine.h b/Code/CoreData/RKManagedObjectSearchEngine.h index 92b00911..64abcf57 100644 --- a/Code/CoreData/RKManagedObjectSearchEngine.h +++ b/Code/CoreData/RKManagedObjectSearchEngine.h @@ -21,7 +21,7 @@ #import "RKSearchEngine.h" @interface RKManagedObjectSearchEngine : NSObject { - RKSearchMode _mode; + RKSearchMode _mode; } /** diff --git a/Code/CoreData/RKManagedObjectSearchEngine.m b/Code/CoreData/RKManagedObjectSearchEngine.m index d2a9f6a2..0740d99b 100644 --- a/Code/CoreData/RKManagedObjectSearchEngine.m +++ b/Code/CoreData/RKManagedObjectSearchEngine.m @@ -33,68 +33,68 @@ static NSMutableCharacterSet* __removeSet; @synthesize mode = _mode; + (id)searchEngine { - RKManagedObjectSearchEngine* searchEngine = [[[RKManagedObjectSearchEngine alloc] init] autorelease]; - return searchEngine; + RKManagedObjectSearchEngine* searchEngine = [[[RKManagedObjectSearchEngine alloc] init] autorelease]; + return searchEngine; } - (id)init { - if (self = [super init]) { - _mode = RKSearchModeOr; - } + if (self = [super init]) { + _mode = RKSearchModeOr; + } - return self; + return self; } #pragma mark - #pragma mark Private - (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]]; - } - return [NSCompoundPredicate performSelector:selector withObject:termPredicates]; + NSMutableArray* termPredicates = [NSMutableArray array]; + for (NSString* searchTerm in searchTerms) { + [termPredicates addObject: + [NSPredicate predicateWithFormat:@"(ANY searchWords.word beginswith %@)", searchTerm]]; + } + return [NSCompoundPredicate performSelector:selector withObject:termPredicates]; } #pragma mark - #pragma mark Public + (NSArray*)tokenizedNormalizedString:(NSString*)string { - if (__removeSet == nil) { - NSMutableCharacterSet* removeSet = [[NSCharacterSet alphanumericCharacterSet] mutableCopy]; - [removeSet formUnionWithCharacterSet:[NSCharacterSet whitespaceCharacterSet]]; - [removeSet invert]; - __removeSet = removeSet; - } + if (__removeSet == nil) { + NSMutableCharacterSet* removeSet = [[NSCharacterSet alphanumericCharacterSet] mutableCopy]; + [removeSet formUnionWithCharacterSet:[NSCharacterSet whitespaceCharacterSet]]; + [removeSet invert]; + __removeSet = removeSet; + } - NSString* scannerString = [[[[string lowercaseString] decomposedStringWithCanonicalMapping] - stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] - stringByReplacingOccurrencesOfString:@"-" withString:@" "]; + NSString* scannerString = [[[[string lowercaseString] decomposedStringWithCanonicalMapping] + stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] + stringByReplacingOccurrencesOfString:@"-" withString:@" "]; - NSArray* tokens = [[[scannerString componentsSeparatedByCharactersInSet:__removeSet] - componentsJoinedByString:@""] componentsSeparatedByString:@" "]; - return tokens; + NSArray* tokens = [[[scannerString componentsSeparatedByCharactersInSet:__removeSet] + componentsJoinedByString:@""] componentsSeparatedByString:@" "]; + return tokens; } - (NSPredicate*)predicateForSearch:(NSString*)searchText { - NSString* searchQuery = [searchText copy]; - NSArray* searchTerms = [RKManagedObjectSearchEngine tokenizedNormalizedString:searchQuery]; - [searchQuery release]; + NSString* searchQuery = [searchText copy]; + NSArray* searchTerms = [RKManagedObjectSearchEngine tokenizedNormalizedString:searchQuery]; + [searchQuery release]; - if ([searchTerms count] == 0) { - return nil; - } + if ([searchTerms count] == 0) { + return nil; + } - if (_mode == RKSearchModeOr) { - return [self predicateForSearch:searchTerms - compoundSelector:@selector(orPredicateWithSubpredicates:)]; - } else if (_mode == RKSearchModeAnd) { - return [self predicateForSearch:searchTerms - compoundSelector:@selector(andPredicateWithSubpredicates:)]; - } else { - return nil; - } + if (_mode == RKSearchModeOr) { + return [self predicateForSearch:searchTerms + compoundSelector:@selector(orPredicateWithSubpredicates:)]; + } else if (_mode == RKSearchModeAnd) { + return [self predicateForSearch:searchTerms + compoundSelector:@selector(andPredicateWithSubpredicates:)]; + } else { + return nil; + } } @end diff --git a/Code/CoreData/RKManagedObjectSeeder.h b/Code/CoreData/RKManagedObjectSeeder.h index 3c1cf4db..c856a81c 100644 --- a/Code/CoreData/RKManagedObjectSeeder.h +++ b/Code/CoreData/RKManagedObjectSeeder.h @@ -39,7 +39,7 @@ extern NSString* const RKDefaultSeedDatabaseFileName; * data immediately available for use within Core Data. */ @interface RKManagedObjectSeeder : NSObject { - RKObjectManager* _manager; + RKObjectManager* _manager; NSObject* _delegate; } diff --git a/Code/CoreData/RKManagedObjectSeeder.m b/Code/CoreData/RKManagedObjectSeeder.m index 32372403..f779984f 100644 --- a/Code/CoreData/RKManagedObjectSeeder.m +++ b/Code/CoreData/RKManagedObjectSeeder.m @@ -47,7 +47,7 @@ NSString* const RKDefaultSeedDatabaseFileName = @"RKSeedDatabase.sqlite"; va_list args; va_start(args, firstFileName); - NSMutableArray* fileNames = [NSMutableArray array]; + NSMutableArray* fileNames = [NSMutableArray array]; for (NSString* fileName = firstFileName; fileName != nil; fileName = va_arg(args, id)) { [fileNames addObject:fileName]; } @@ -67,8 +67,8 @@ NSString* const RKDefaultSeedDatabaseFileName = @"RKSeedDatabase.sqlite"; - (id)initWithObjectManager:(RKObjectManager*)manager { self = [self init]; - if (self) { - _manager = [manager retain]; + if (self) { + _manager = [manager retain]; // If the user hasn't configured an object store, set one up for them if (nil == _manager.objectStore) { @@ -77,14 +77,14 @@ NSString* const RKDefaultSeedDatabaseFileName = @"RKSeedDatabase.sqlite"; // Delete any existing persistent store [_manager.objectStore deletePersistentStore]; - } + } - return self; + return self; } - (void)dealloc { - [_manager release]; - [super dealloc]; + [_manager release]; + [super dealloc]; } - (NSString*)pathToSeedDatabase { @@ -94,7 +94,7 @@ NSString* const RKDefaultSeedDatabaseFileName = @"RKSeedDatabase.sqlite"; - (void)seedObjectsFromFiles:(NSString*)firstFileName, ... { va_list args; va_start(args, firstFileName); - NSMutableArray* fileNames = [NSMutableArray array]; + NSMutableArray* fileNames = [NSMutableArray array]; for (NSString* fileName = firstFileName; fileName != nil; fileName = va_arg(args, id)) { [fileNames addObject:fileName]; } @@ -111,16 +111,16 @@ NSString* const RKDefaultSeedDatabaseFileName = @"RKSeedDatabase.sqlite"; - (void)seedObjectsFromFile:(NSString *)fileName withObjectMapping:(RKObjectMapping *)nilOrObjectMapping bundle:(NSBundle *)nilOrBundle { - NSError* error = nil; + NSError* error = nil; - if (nilOrBundle == nil) { - nilOrBundle = [NSBundle mainBundle]; - } + 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) { + if (payload) { NSString* MIMEType = [fileName MIMETypeForPathExtension]; if (MIMEType == nil) { // Default the MIME type to the value of the Accept header if we couldn't detect it... @@ -147,7 +147,7 @@ NSString* const RKDefaultSeedDatabaseFileName = @"RKSeedDatabase.sqlite"; } NSArray* mappedObjects = [result asCollection]; - NSAssert1([mappedObjects isKindOfClass:[NSArray class]], @"Expected an NSArray of objects, got %@", mappedObjects); + NSAssert1([mappedObjects isKindOfClass:[NSArray class]], @"Expected an NSArray of objects, got %@", mappedObjects); // Inform the delegate if (self.delegate) { @@ -156,28 +156,28 @@ NSString* const RKDefaultSeedDatabaseFileName = @"RKSeedDatabase.sqlite"; } } - RKLogInfo(@"Seeded %lu objects from %@...", (unsigned long) [mappedObjects count], [NSString stringWithFormat:@"%@", fileName]); - } else { - RKLogError(@"Unable to read file %@: %@", fileName, [error localizedDescription]); - } + RKLogInfo(@"Seeded %lu objects from %@...", (unsigned long) [mappedObjects count], [NSString stringWithFormat:@"%@", fileName]); + } else { + RKLogError(@"Unable to read file %@: %@", fileName, [error localizedDescription]); + } } - (void)finalizeSeedingAndExit { - NSError *error = nil; + NSError *error = nil; BOOL success = [[_manager objectStore] save:&error]; - if (! success) { - RKLogError(@"[RestKit] RKManagedObjectSeeder: Error saving object context: %@", [error localizedDescription]); - } + 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]; - RKLogInfo(@"A seeded database has been generated at '%@'. " + 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); - exit(1); + exit(1); } @end diff --git a/Code/CoreData/RKManagedObjectStore.h b/Code/CoreData/RKManagedObjectStore.h index 5fc35267..75bfd8e6 100644 --- a/Code/CoreData/RKManagedObjectStore.h +++ b/Code/CoreData/RKManagedObjectStore.h @@ -47,11 +47,11 @@ extern NSString* const RKManagedObjectStoreDidFailSaveNotification; /////////////////////////////////////////////////////////////////// @interface RKManagedObjectStore : NSObject { - NSObject* _delegate; - NSString* _storeFilename; - NSString* _pathToStoreFile; + NSObject* _delegate; + NSString* _storeFilename; + NSString* _pathToStoreFile; NSManagedObjectModel* _managedObjectModel; - NSPersistentStoreCoordinator* _persistentStoreCoordinator; + NSPersistentStoreCoordinator* _persistentStoreCoordinator; } // The delegate for this object store @@ -143,13 +143,13 @@ extern NSString* const RKManagedObjectStoreDidFailSaveNotification; - (void)deletePersistentStore; /** - * Retrieves a model object from the appropriate context using the objectId + * Retrieves a model object from the appropriate context using the objectId */ - (NSManagedObject*)objectWithID:(NSManagedObjectID*)objectID; /** - * Retrieves a array of model objects from the appropriate context using - * an array of NSManagedObjectIDs + * Retrieves a array of model objects from the appropriate context using + * an array of NSManagedObjectIDs */ - (NSArray*)objectsWithIDs:(NSArray*)objectIDs; diff --git a/Code/CoreData/RKManagedObjectStore.m b/Code/CoreData/RKManagedObjectStore.m index 02bba589..186a35b5 100644 --- a/Code/CoreData/RKManagedObjectStore.m +++ b/Code/CoreData/RKManagedObjectStore.m @@ -75,7 +75,7 @@ static RKManagedObjectStore *defaultObjectStore = nil; + (void)deleteStoreAtPath:(NSString *)path { NSURL* storeURL = [NSURL fileURLWithPath:path]; - NSError* error = nil; + 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); @@ -104,35 +104,35 @@ static RKManagedObjectStore *defaultObjectStore = nil; } - (id)initWithStoreFilename:(NSString*)storeFilename { - return [self initWithStoreFilename:storeFilename inDirectory:nil usingSeedDatabaseName:nil managedObjectModel:nil delegate:nil]; + 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 { self = [self init]; - if (self) { - _storeFilename = [storeFilename retain]; + if (self) { + _storeFilename = [storeFilename retain]; - if (nilOrDirectoryPath == nil) { - nilOrDirectoryPath = [RKDirectory applicationDataDirectory]; - } else { - BOOL isDir; - NSAssert1([[NSFileManager defaultManager] fileExistsAtPath:nilOrDirectoryPath isDirectory:&isDir] && isDir == YES, @"Specified storage directory exists", nilOrDirectoryPath); - } - _pathToStoreFile = [[nilOrDirectoryPath stringByAppendingPathComponent:_storeFilename] retain]; + if (nilOrDirectoryPath == nil) { + nilOrDirectoryPath = [RKDirectory applicationDataDirectory]; + } else { + BOOL isDir; + NSAssert1([[NSFileManager defaultManager] fileExistsAtPath:nilOrDirectoryPath isDirectory:&isDir] && isDir == YES, @"Specified storage directory exists", nilOrDirectoryPath); + } + _pathToStoreFile = [[nilOrDirectoryPath stringByAppendingPathComponent:_storeFilename] retain]; if (nilOrManagedObjectModel == nil) { // NOTE: allBundles permits Core Data setup in unit tests - nilOrManagedObjectModel = [NSManagedObjectModel mergedModelFromBundles:[NSBundle allBundles]]; + nilOrManagedObjectModel = [NSManagedObjectModel mergedModelFromBundles:[NSBundle allBundles]]; } - NSMutableArray* allManagedObjectModels = [NSMutableArray arrayWithObject:nilOrManagedObjectModel]; - _managedObjectModel = [[NSManagedObjectModel modelByMergingModels:allManagedObjectModels] retain]; + NSMutableArray* allManagedObjectModels = [NSMutableArray arrayWithObject:nilOrManagedObjectModel]; + _managedObjectModel = [[NSManagedObjectModel modelByMergingModels:allManagedObjectModels] retain]; _delegate = delegate; if (nilOrNameOfSeedDatabaseInMainBundle) { [self createStoreIfNecessaryUsingSeedDatabase:nilOrNameOfSeedDatabaseInMainBundle]; } - [self createPersistentStoreCoordinator]; + [self createPersistentStoreCoordinator]; self.primaryManagedObjectContext = [[self newManagedObjectContext] autorelease]; _cacheStrategy = [RKInMemoryManagedObjectCache new]; @@ -144,9 +144,9 @@ static RKManagedObjectStore *defaultObjectStore = nil; if (! defaultObjectStore) { [RKManagedObjectStore setDefaultObjectStore:self]; } - } + } - return self; + return self; } - (void)setThreadLocalObject:(id)value forKey:(id)key { @@ -191,24 +191,24 @@ static RKManagedObjectStore *defaultObjectStore = nil; } - (void)dealloc { - [[NSNotificationCenter defaultCenter] removeObserver:self]; + [[NSNotificationCenter defaultCenter] removeObserver:self]; [self clearThreadLocalStorage]; - [_storeFilename release]; - _storeFilename = nil; - [_pathToStoreFile release]; - _pathToStoreFile = nil; + [_storeFilename release]; + _storeFilename = nil; + [_pathToStoreFile release]; + _pathToStoreFile = nil; [_managedObjectModel release]; - _managedObjectModel = nil; + _managedObjectModel = nil; [_persistentStoreCoordinator release]; - _persistentStoreCoordinator = nil; + _persistentStoreCoordinator = nil; [_cacheStrategy release]; _cacheStrategy = nil; [primaryManagedObjectContext release]; primaryManagedObjectContext = nil; - [super dealloc]; + [super dealloc]; } /** @@ -216,75 +216,75 @@ static RKManagedObjectStore *defaultObjectStore = nil; message to the application's managed object context. */ - (BOOL)save:(NSError **)error { - NSManagedObjectContext* moc = [self managedObjectContextForCurrentThread]; + NSManagedObjectContext* moc = [self managedObjectContextForCurrentThread]; NSError *localError = nil; - @try { - if (![moc save:&localError]) { - if (self.delegate != nil && [self.delegate respondsToSelector:@selector(managedObjectStore:didFailToSaveContext:error:exception:)]) { - [self.delegate managedObjectStore:self didFailToSaveContext:moc error:localError exception:nil]; - } + @try { + if (![moc save:&localError]) { + if (self.delegate != nil && [self.delegate respondsToSelector:@selector(managedObjectStore:didFailToSaveContext:error:exception:)]) { + [self.delegate managedObjectStore:self didFailToSaveContext:moc error:localError exception:nil]; + } - NSDictionary* userInfo = [NSDictionary dictionaryWithObject:localError forKey:@"error"]; - [[NSNotificationCenter defaultCenter] postNotificationName:RKManagedObjectStoreDidFailSaveNotification object:self userInfo:userInfo]; + NSDictionary* userInfo = [NSDictionary dictionaryWithObject:localError forKey:@"error"]; + [[NSNotificationCenter defaultCenter] postNotificationName:RKManagedObjectStoreDidFailSaveNotification object:self userInfo:userInfo]; - if ([[localError domain] isEqualToString:@"NSCocoaErrorDomain"]) { - NSDictionary *userInfo = [localError userInfo]; - NSArray *errors = [userInfo valueForKey:@"NSDetailedErrors"]; - if (errors) { - for (NSError *detailedError in errors) { - NSDictionary *subUserInfo = [detailedError userInfo]; - RKLogError(@"Core Data Save Error\n \ - NSLocalizedDescription:\t\t%@\n \ - NSValidationErrorKey:\t\t\t%@\n \ - NSValidationErrorPredicate:\t%@\n \ - NSValidationErrorObject:\n%@\n", - [subUserInfo valueForKey:@"NSLocalizedDescription"], - [subUserInfo valueForKey:@"NSValidationErrorKey"], - [subUserInfo valueForKey:@"NSValidationErrorPredicate"], - [subUserInfo valueForKey:@"NSValidationErrorObject"]); - } - } - else { - RKLogError(@"Core Data Save Error\n \ - NSLocalizedDescription:\t\t%@\n \ - NSValidationErrorKey:\t\t\t%@\n \ - NSValidationErrorPredicate:\t%@\n \ - NSValidationErrorObject:\n%@\n", - [userInfo valueForKey:@"NSLocalizedDescription"], - [userInfo valueForKey:@"NSValidationErrorKey"], - [userInfo valueForKey:@"NSValidationErrorPredicate"], - [userInfo valueForKey:@"NSValidationErrorObject"]); - } - } + if ([[localError domain] isEqualToString:@"NSCocoaErrorDomain"]) { + NSDictionary *userInfo = [localError userInfo]; + NSArray *errors = [userInfo valueForKey:@"NSDetailedErrors"]; + if (errors) { + for (NSError *detailedError in errors) { + NSDictionary *subUserInfo = [detailedError userInfo]; + RKLogError(@"Core Data Save Error\n \ + NSLocalizedDescription:\t\t%@\n \ + NSValidationErrorKey:\t\t\t%@\n \ + NSValidationErrorPredicate:\t%@\n \ + NSValidationErrorObject:\n%@\n", + [subUserInfo valueForKey:@"NSLocalizedDescription"], + [subUserInfo valueForKey:@"NSValidationErrorKey"], + [subUserInfo valueForKey:@"NSValidationErrorPredicate"], + [subUserInfo valueForKey:@"NSValidationErrorObject"]); + } + } + else { + RKLogError(@"Core Data Save Error\n \ + NSLocalizedDescription:\t\t%@\n \ + NSValidationErrorKey:\t\t\t%@\n \ + NSValidationErrorPredicate:\t%@\n \ + NSValidationErrorObject:\n%@\n", + [userInfo valueForKey:@"NSLocalizedDescription"], + [userInfo valueForKey:@"NSValidationErrorKey"], + [userInfo valueForKey:@"NSValidationErrorPredicate"], + [userInfo valueForKey:@"NSValidationErrorObject"]); + } + } if (error) { *error = localError; } - return NO; - } - } - @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]; - } - else { - @throw; - } - } + return NO; + } + } + @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]; + } + else { + @throw; + } + } - return YES; + return YES; } - (NSManagedObjectContext *)newManagedObjectContext { - NSManagedObjectContext *managedObjectContext = [[NSManagedObjectContext alloc] init]; - [managedObjectContext setPersistentStoreCoordinator:self.persistentStoreCoordinator]; - [managedObjectContext setUndoManager:nil]; - [managedObjectContext setMergePolicy:NSMergeByPropertyStoreTrumpMergePolicy]; + NSManagedObjectContext *managedObjectContext = [[NSManagedObjectContext alloc] init]; + [managedObjectContext setPersistentStoreCoordinator:self.persistentStoreCoordinator]; + [managedObjectContext setUndoManager:nil]; + [managedObjectContext setMergePolicy:NSMergeByPropertyStoreTrumpMergePolicy]; managedObjectContext.managedObjectStore = self; - return managedObjectContext; + return managedObjectContext; } - (void)createStoreIfNecessaryUsingSeedDatabase:(NSString*)seedDatabase { @@ -293,13 +293,13 @@ static RKManagedObjectStore *defaultObjectStore = 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]; - } else { - RKLogError(@"Encountered an error during seed database copy: %@", [error localizedDescription]); - } + if (self.delegate != nil && [self.delegate respondsToSelector:@selector(managedObjectStore:didFailToCopySeedDatabase:error:)]) { + [self.delegate managedObjectStore:self didFailToCopySeedDatabase:seedDatabase error:error]; + } else { + RKLogError(@"Encountered an error during seed database copy: %@", [error localizedDescription]); + } } NSAssert1([[NSFileManager defaultManager] fileExistsAtPath:seedDatabasePath], @"Seed database not found at path '%@'!", seedDatabasePath); } @@ -308,28 +308,28 @@ static RKManagedObjectStore *defaultObjectStore = nil; - (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]; + NSURL *storeURL = [NSURL fileURLWithPath:self.pathToStoreFile]; - NSError *error; + NSError *error; _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:_managedObjectModel]; - // Allow inferred migration from the original version of the application. - NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys: - [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, - [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil]; + // Allow inferred migration from the original version of the application. + NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys: + [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, + [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil]; - if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]) { - if (self.delegate != nil && [self.delegate respondsToSelector:@selector(managedObjectStore:didFailToCreatePersistentStoreCoordinatorWithError:)]) { - [self.delegate managedObjectStore:self didFailToCreatePersistentStoreCoordinatorWithError:error]; - } else { - NSAssert(NO, @"Managed object store failed to create persistent store coordinator: %@", error); - } + if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]) { + if (self.delegate != nil && [self.delegate respondsToSelector:@selector(managedObjectStore:didFailToCreatePersistentStoreCoordinatorWithError:)]) { + [self.delegate managedObjectStore:self didFailToCreatePersistentStoreCoordinatorWithError:error]; + } else { + NSAssert(NO, @"Managed object store failed to create persistent store coordinator: %@", error); + } } } - (void)deletePersistentStoreUsingSeedDatabaseName:(NSString *)seedFile { - NSURL* storeURL = [NSURL fileURLWithPath:self.pathToStoreFile]; - NSError* error = nil; + 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:)]) { @@ -343,21 +343,21 @@ static RKManagedObjectStore *defaultObjectStore = nil; RKLogWarning(@"Asked to delete persistent store but no store file exists at path: %@", storeURL.path); } - [_persistentStoreCoordinator release]; - _persistentStoreCoordinator = nil; + [_persistentStoreCoordinator release]; + _persistentStoreCoordinator = nil; - if (seedFile) { + if (seedFile) { [self createStoreIfNecessaryUsingSeedDatabase:seedFile]; } - [self createPersistentStoreCoordinator]; + [self createPersistentStoreCoordinator]; // Recreate the MOC self.primaryManagedObjectContext = [[self newManagedObjectContext] autorelease]; } - (void)deletePersistentStore { - [self deletePersistentStoreUsingSeedDatabaseName:nil]; + [self deletePersistentStoreUsingSeedDatabaseName:nil]; } - (NSManagedObjectContext *)managedObjectContextForCurrentThread { @@ -366,34 +366,34 @@ static RKManagedObjectStore *defaultObjectStore = nil; } // Background threads leverage thread-local storage - NSManagedObjectContext* managedObjectContext = [self threadLocalObjectForKey:RKManagedObjectStoreThreadDictionaryContextKey]; - if (!managedObjectContext) { - managedObjectContext = [self newManagedObjectContext]; + NSManagedObjectContext* managedObjectContext = [self threadLocalObjectForKey:RKManagedObjectStoreThreadDictionaryContextKey]; + if (!managedObjectContext) { + managedObjectContext = [self newManagedObjectContext]; // Store into thread local storage dictionary [self setThreadLocalObject:managedObjectContext forKey:RKManagedObjectStoreThreadDictionaryContextKey]; - [managedObjectContext release]; + [managedObjectContext release]; // If we are a background Thread MOC, we need to inform the main thread on save [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mergeChanges:) name:NSManagedObjectContextDidSaveNotification object:managedObjectContext]; - } + } - return managedObjectContext; + return managedObjectContext; } - (void)mergeChangesOnMainThreadWithNotification:(NSNotification*)notification { - assert([NSThread isMainThread]); - [self.primaryManagedObjectContext performSelectorOnMainThread:@selector(mergeChangesFromContextDidSaveNotification:) - withObject:notification - waitUntilDone:YES]; + assert([NSThread isMainThread]); + [self.primaryManagedObjectContext performSelectorOnMainThread:@selector(mergeChangesFromContextDidSaveNotification:) + withObject:notification + waitUntilDone:YES]; } - (void)mergeChanges:(NSNotification *)notification { - // Merge changes into the main context on the main thread - [self performSelectorOnMainThread:@selector(mergeChangesOnMainThreadWithNotification:) withObject:notification waitUntilDone:YES]; + // Merge changes into the main context on the main thread + [self performSelectorOnMainThread:@selector(mergeChangesOnMainThreadWithNotification:) withObject:notification waitUntilDone:YES]; } #pragma mark - @@ -401,18 +401,18 @@ static RKManagedObjectStore *defaultObjectStore = nil; - (NSManagedObject*)objectWithID:(NSManagedObjectID *)objectID { NSAssert(objectID, @"Cannot fetch a managedObject with a nil objectID"); - return [[self managedObjectContextForCurrentThread] objectWithID:objectID]; + return [[self managedObjectContextForCurrentThread] objectWithID:objectID]; } - (NSArray*)objectsWithIDs:(NSArray*)objectIDs { - NSMutableArray* objects = [[NSMutableArray alloc] init]; - for (NSManagedObjectID* objectID in objectIDs) { - [objects addObject:[self objectWithID:objectID]]; - } - NSArray* objectArray = [NSArray arrayWithArray:objects]; - [objects release]; + NSMutableArray* objects = [[NSMutableArray alloc] init]; + for (NSManagedObjectID* objectID in objectIDs) { + [objects addObject:[self objectWithID:objectID]]; + } + NSArray* objectArray = [NSArray arrayWithArray:objects]; + [objects release]; - return objectArray; + return objectArray; } @end diff --git a/Code/CoreData/RKObjectPropertyInspector+CoreData.m b/Code/CoreData/RKObjectPropertyInspector+CoreData.m index 98425ab0..9767b692 100644 --- a/Code/CoreData/RKObjectPropertyInspector+CoreData.m +++ b/Code/CoreData/RKObjectPropertyInspector+CoreData.m @@ -35,9 +35,9 @@ RK_FIX_CATEGORY_BUG(RKObjectPropertyInspector_CoreData) - (NSDictionary *)propertyNamesAndTypesForEntity:(NSEntityDescription*)entity { NSMutableDictionary* propertyNamesAndTypes = [_cachedPropertyNamesAndTypes objectForKey:[entity name]]; - if (propertyNamesAndTypes) { - return propertyNamesAndTypes; - } + if (propertyNamesAndTypes) { + return propertyNamesAndTypes; + } propertyNamesAndTypes = [NSMutableDictionary dictionary]; for (NSString* name in [entity attributesByName]) { diff --git a/Code/CoreData/RKSearchableManagedObject.m b/Code/CoreData/RKSearchableManagedObject.m index 9e6a56a4..df667e91 100644 --- a/Code/CoreData/RKSearchableManagedObject.m +++ b/Code/CoreData/RKSearchableManagedObject.m @@ -32,18 +32,18 @@ + (NSArray *)searchableAttributes { - return [NSArray array]; + return [NSArray array]; } + (NSPredicate *)predicateForSearchWithText:(NSString *)searchText searchMode:(RKSearchMode)mode { - if (searchText == nil) { - return nil; - } else { + if (searchText == nil) { + return nil; + } else { RKManagedObjectSearchEngine *searchEngine = [RKManagedObjectSearchEngine searchEngine]; searchEngine.mode = mode; - return [searchEngine predicateForSearch:searchText]; - } + return [searchEngine predicateForSearch:searchText]; + } } - (void)refreshSearchWords @@ -75,7 +75,7 @@ self.searchWords = searchWords; RKLogTrace(@"Generating searchWords: %@", [searchWords valueForKey:RKSearchWordPrimaryKeyAttribute]); - [pool drain]; + [pool drain]; } @end diff --git a/Code/Network/NSData+RKAdditions.m b/Code/Network/NSData+RKAdditions.m index 567b332d..5ae5fa3e 100644 --- a/Code/Network/NSData+RKAdditions.m +++ b/Code/Network/NSData+RKAdditions.m @@ -27,19 +27,19 @@ RK_FIX_CATEGORY_BUG(NSData_RKAdditions) @implementation NSData (RKAdditions) - (NSString *)MD5 { - // Create byte array of unsigned chars - unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH]; + // 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); + // Create 16 byte MD5 hash value, store in buffer + 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]; - for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) { - [output appendFormat:@"%02x",md5Buffer[i]]; - } + // Convert unsigned char buffer to NSString of hex values + NSMutableString* output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2]; + for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) { + [output appendFormat:@"%02x",md5Buffer[i]]; + } - return output; + return output; } @end diff --git a/Code/Network/NSDictionary+RKRequestSerialization.m b/Code/Network/NSDictionary+RKRequestSerialization.m index 991da1b6..0c5c19fb 100644 --- a/Code/Network/NSDictionary+RKRequestSerialization.m +++ b/Code/Network/NSDictionary+RKRequestSerialization.m @@ -29,12 +29,12 @@ RK_FIX_CATEGORY_BUG(NSDictionary_RKRequestSerialization) - (NSString *)HTTPHeaderValueForContentType { - return RKMIMETypeFormURLEncoded; + return RKMIMETypeFormURLEncoded; } - (NSData *)HTTPBody { - return [[self URLEncodedString] dataUsingEncoding:NSUTF8StringEncoding]; + return [[self URLEncodedString] dataUsingEncoding:NSUTF8StringEncoding]; } @end diff --git a/Code/Network/NSObject+URLEncoding.m b/Code/Network/NSObject+URLEncoding.m index be5f1cef..54c8a927 100644 --- a/Code/Network/NSObject+URLEncoding.m +++ b/Code/Network/NSObject+URLEncoding.m @@ -12,13 +12,13 @@ @implementation NSObject (URLEncoding) - (NSString*)URLEncodedString { - NSString *string = [NSString stringWithFormat:@"%@", self]; - NSString *encodedString = (NSString*)CFURLCreateStringByAddingPercentEscapes(NULL, - (CFStringRef)string, - NULL, - (CFStringRef)@"!*'();:@&=+$,/?%#[]", - kCFStringEncodingUTF8); - return [encodedString autorelease]; + NSString *string = [NSString stringWithFormat:@"%@", self]; + NSString *encodedString = (NSString*)CFURLCreateStringByAddingPercentEscapes(NULL, + (CFStringRef)string, + NULL, + (CFStringRef)@"!*'();:@&=+$,/?%#[]", + kCFStringEncodingUTF8); + return [encodedString autorelease]; } @end diff --git a/Code/Network/RKClient.h b/Code/Network/RKClient.h index 92b3f195..fb450ef7 100644 --- a/Code/Network/RKClient.h +++ b/Code/Network/RKClient.h @@ -95,24 +95,24 @@ @see RKRequestSerializable */ @interface RKClient : NSObject { - RKURL *_baseURL; + RKURL *_baseURL; RKRequestAuthenticationType _authenticationType; - NSString *_username; - NSString *_password; + 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; + NSMutableDictionary *_HTTPHeaders; + RKReachabilityObserver *_reachabilityObserver; + NSString *_serviceUnavailableAlertTitle; + NSString *_serviceUnavailableAlertMessage; + BOOL _serviceUnavailableAlertEnabled; RKRequestQueue *_requestQueue; - RKRequestCache *_requestCache; - RKRequestCachePolicy _cachePolicy; + RKRequestCache *_requestCache; + RKRequestCachePolicy _cachePolicy; NSMutableSet *_additionalRootCertificates; BOOL _disableCertificateValidation; NSStringEncoding _defaultHTTPEncoding; diff --git a/Code/Network/RKClient.m b/Code/Network/RKClient.m index 9a04860a..031b2b02 100644 --- a/Code/Network/RKClient.m +++ b/Code/Network/RKClient.m @@ -98,12 +98,12 @@ NSString *RKPathAppendQueryParams(NSString *resourcePath, NSDictionary *queryPar @synthesize runLoopMode = _runLoopMode; + (RKClient *)sharedClient { - return sharedClient; + return sharedClient; } + (void)setSharedClient:(RKClient *)client { - [sharedClient release]; - sharedClient = [client retain]; + [sharedClient release]; + sharedClient = [client retain]; } + (RKClient *)clientWithBaseURLString:(NSString *)baseURLString { @@ -111,21 +111,21 @@ NSString *RKPathAppendQueryParams(NSString *resourcePath, NSDictionary *queryPar } + (RKClient *)clientWithBaseURL:(NSURL *)baseURL { - RKClient *client = [[[self alloc] initWithBaseURL:baseURL] autorelease]; - return client; + RKClient *client = [[[self alloc] initWithBaseURL:baseURL] autorelease]; + return client; } + (RKClient *)clientWithBaseURL:(NSString *)baseURL username:(NSString *)username password:(NSString *)password { - RKClient *client = [RKClient clientWithBaseURLString:baseURL]; + RKClient *client = [RKClient clientWithBaseURLString:baseURL]; client.authenticationType = RKRequestAuthenticationTypeHTTPBasic; - client.username = username; - client.password = password; - return client; + client.username = username; + client.password = password; + return client; } - (id)init { self = [super init]; - if (self) { + if (self) { self.HTTPHeaders = [[NSMutableDictionary alloc] init]; self.additionalRootCertificates = [[NSMutableSet alloc] init]; self.defaultHTTPEncoding = NSUTF8StringEncoding; @@ -144,9 +144,9 @@ NSString *RKPathAppendQueryParams(NSString *resourcePath, NSDictionary *queryPar [self addObserver:self forKeyPath:@"reachabilityObserver" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil]; [self addObserver:self forKeyPath:@"baseURL" options:NSKeyValueObservingOptionNew context:nil]; [self addObserver:self forKeyPath:@"requestQueue" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld | NSKeyValueObservingOptionInitial context:nil]; - } + } - return self; + return self; } - (id)initWithBaseURL:(NSURL *)baseURL { @@ -204,20 +204,20 @@ NSString *RKPathAppendQueryParams(NSString *resourcePath, NSDictionary *queryPar } - (BOOL)isNetworkReachable { - BOOL isNetworkReachable = YES; - if (self.reachabilityObserver) { - isNetworkReachable = [self.reachabilityObserver isNetworkReachable]; - } + BOOL isNetworkReachable = YES; + if (self.reachabilityObserver) { + isNetworkReachable = [self.reachabilityObserver isNetworkReachable]; + } - return isNetworkReachable; + return isNetworkReachable; } - (void)configureRequest:(RKRequest *)request { - request.additionalHTTPHeaders = _HTTPHeaders; + request.additionalHTTPHeaders = _HTTPHeaders; request.authenticationType = self.authenticationType; - request.username = self.username; - request.password = self.password; - request.cachePolicy = self.cachePolicy; + request.username = self.username; + request.password = self.password; + request.cachePolicy = self.cachePolicy; request.cache = self.requestCache; request.queue = self.requestQueue; request.reachabilityObserver = self.reachabilityObserver; @@ -249,7 +249,7 @@ NSString *RKPathAppendQueryParams(NSString *resourcePath, NSDictionary *queryPar } - (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)header { - [_HTTPHeaders setValue:value forKey:header]; + [_HTTPHeaders setValue:value forKey:header]; } - (void)addRootCertificate:(SecCertificateRef)cert { @@ -339,14 +339,14 @@ NSString *RKPathAppendQueryParams(NSString *resourcePath, NSDictionary *queryPar - (RKRequest *)requestWithResourcePath:(NSString *)resourcePath { RKRequest *request = [[RKRequest alloc] initWithURL:[self.baseURL URLByAppendingResourcePath:resourcePath]]; - [self configureRequest:request]; - [request autorelease]; + [self configureRequest:request]; + [request autorelease]; - return request; + return request; } - (RKRequest *)requestWithResourcePath:(NSString *)resourcePath delegate:(NSObject *)delegate { - RKRequest *request = [self requestWithResourcePath:resourcePath]; + RKRequest *request = [self requestWithResourcePath:resourcePath]; request.delegate = delegate; return request; @@ -357,43 +357,43 @@ NSString *RKPathAppendQueryParams(NSString *resourcePath, NSDictionary *queryPar /////////////////////////////////////////////////////////////////////////////////////////////////////////// - (RKRequest *)load:(NSString *)resourcePath method:(RKRequestMethod)method params:(NSObject *)params delegate:(id)delegate { - RKURL* resourcePathURL = nil; - if (method == RKRequestMethodGET) { + RKURL* resourcePathURL = nil; + if (method == RKRequestMethodGET) { resourcePathURL = [self.baseURL URLByAppendingResourcePath:resourcePath queryParameters:(NSDictionary *)params]; - } else { - resourcePathURL = [self.baseURL URLByAppendingResourcePath:resourcePath]; - } - RKRequest *request = [RKRequest requestWithURL:resourcePathURL]; + } else { + resourcePathURL = [self.baseURL URLByAppendingResourcePath:resourcePath]; + } + RKRequest *request = [RKRequest requestWithURL:resourcePathURL]; request.delegate = delegate; - [self configureRequest:request]; - request.method = method; - if (method != RKRequestMethodGET) { - request.params = params; - } + [self configureRequest:request]; + request.method = method; + if (method != RKRequestMethodGET) { + request.params = params; + } [request send]; - return request; + return request; } - (RKRequest *)get:(NSString *)resourcePath delegate:(id)delegate { - return [self load:resourcePath method:RKRequestMethodGET params:nil delegate:delegate]; + return [self load:resourcePath method:RKRequestMethodGET params:nil delegate:delegate]; } - (RKRequest *)get:(NSString *)resourcePath queryParameters:(NSDictionary *)queryParameters delegate:(id)delegate { - return [self load:resourcePath method:RKRequestMethodGET params:queryParameters delegate:delegate]; + return [self load:resourcePath method:RKRequestMethodGET params:queryParameters delegate:delegate]; } - (RKRequest *)post:(NSString *)resourcePath params:(NSObject *)params delegate:(id)delegate { - return [self load:resourcePath method:RKRequestMethodPOST params:params delegate:delegate]; + return [self load:resourcePath method:RKRequestMethodPOST params:params delegate:delegate]; } - (RKRequest *)put:(NSString *)resourcePath params:(NSObject *)params delegate:(id)delegate { - return [self load:resourcePath method:RKRequestMethodPUT params:params delegate:delegate]; + return [self load:resourcePath method:RKRequestMethodPUT params:params delegate:delegate]; } - (RKRequest *)delete:(NSString *)resourcePath delegate:(id)delegate { - return [self load:resourcePath method:RKRequestMethodDELETE params:nil delegate:delegate]; + return [self load:resourcePath method:RKRequestMethodDELETE params:nil delegate:delegate]; } - (void)serviceDidBecomeUnavailableNotification:(NSNotification *)notification { @@ -467,7 +467,7 @@ NSString *RKPathAppendQueryParams(NSString *resourcePath, NSDictionary *queryPar } - (NSString *)resourcePath:(NSString *)resourcePath withQueryParams:(NSDictionary *)queryParams { - return RKPathAppendQueryParams(resourcePath, queryParams); + return RKPathAppendQueryParams(resourcePath, queryParams); } - (NSURL *)URLForResourcePath:(NSString *)resourcePath { @@ -475,7 +475,7 @@ NSString *RKPathAppendQueryParams(NSString *resourcePath, NSDictionary *queryPar } - (NSString *)URLPathForResourcePath:(NSString *)resourcePath { - return [[self URLForResourcePath:resourcePath] absoluteString]; + return [[self URLForResourcePath:resourcePath] absoluteString]; } - (NSURL *)URLForResourcePath:(NSString *)resourcePath queryParams:(NSDictionary *)queryParams { diff --git a/Code/Network/RKOAuthClient.h b/Code/Network/RKOAuthClient.h index 4d026c9c..1b051d94 100644 --- a/Code/Network/RKOAuthClient.h +++ b/Code/Network/RKOAuthClient.h @@ -98,9 +98,9 @@ typedef enum RKOAuthClientErrors { @see RKOAuthClientDelegate */ @interface RKOAuthClient : NSObject { - NSString *_clientID; + NSString *_clientID; NSString *_clientSecret; - NSString *_authorizationCode; + NSString *_authorizationCode; NSString *_authorizationURL; NSString *_callbackURL; NSString *_accessToken; diff --git a/Code/Network/RKParamsAttachment.h b/Code/Network/RKParamsAttachment.h index 4b8c932a..675c1a02 100644 --- a/Code/Network/RKParamsAttachment.h +++ b/Code/Network/RKParamsAttachment.h @@ -34,7 +34,7 @@ NSString *_fileName; NSString *_MIMEType; - @private + @private NSString *_filePath; NSData *_body; NSInputStream *_bodyStream; diff --git a/Code/Network/RKParamsAttachment.m b/Code/Network/RKParamsAttachment.m index 324c4a7d..e62413f6 100644 --- a/Code/Network/RKParamsAttachment.m +++ b/Code/Network/RKParamsAttachment.m @@ -43,63 +43,63 @@ extern NSString* const kRKStringBoundary; - (id)initWithName:(NSString *)name { self = [self init]; - if (self) { + if (self) { self.name = name; self.fileName = name; - } + } - return self; + return self; } - (id)initWithName:(NSString *)name value:(id)value { - if ((self = [self initWithName:name])) { - if ([value respondsToSelector:@selector(dataUsingEncoding:)]) { + if ((self = [self initWithName:name])) { + if ([value respondsToSelector:@selector(dataUsingEncoding:)]) { _body = [[(NSString*)value dataUsingEncoding:NSUTF8StringEncoding] retain]; - } else { - _body = [[[NSString stringWithFormat:@"%@", value] dataUsingEncoding:NSUTF8StringEncoding] retain]; - } + } else { + _body = [[[NSString stringWithFormat:@"%@", value] dataUsingEncoding:NSUTF8StringEncoding] retain]; + } - _bodyStream = [[NSInputStream alloc] initWithData:_body]; - _bodyLength = [_body length]; + _bodyStream = [[NSInputStream alloc] initWithData:_body]; + _bodyLength = [_body length]; _value = [value retain]; - } + } - return self; + return self; } - (id)initWithName:(NSString*)name data:(NSData*)data { self = [self initWithName:name]; - if (self) { + if (self) { _body = [data retain]; - _bodyStream = [[NSInputStream alloc] initWithData:data]; - _bodyLength = [data length]; - } + _bodyStream = [[NSInputStream alloc] initWithData:data]; + _bodyLength = [data length]; + } - return self; + return self; } - (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); + if (self) { + NSAssert1([[NSFileManager defaultManager] fileExistsAtPath:filePath], @"Expected file to exist at path: %@", filePath); _filePath = [filePath retain]; _fileName = [[filePath lastPathComponent] retain]; NSString *MIMEType = [filePath MIMETypeForPathExtension]; if (! MIMEType) MIMEType = @"application/octet-stream"; - _MIMEType = [MIMEType retain]; - _bodyStream = [[NSInputStream alloc] initWithFileAtPath:filePath]; + _MIMEType = [MIMEType retain]; + _bodyStream = [[NSInputStream alloc] initWithFileAtPath:filePath]; - NSError* error; - NSDictionary* attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:&error]; - if (attributes) { - _bodyLength = [[attributes objectForKey:NSFileSize] unsignedIntegerValue]; - } - else { - RKLogError(@"Encountered an error while determining file size: %@", error); - } - } + NSError* error; + NSDictionary* attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:&error]; + if (attributes) { + _bodyLength = [[attributes objectForKey:NSFileSize] unsignedIntegerValue]; + } + else { + RKLogError(@"Encountered an error while determining file size: %@", error); + } + } - return self; + return self; } - (void)dealloc { @@ -121,35 +121,35 @@ extern NSString* const kRKStringBoundary; } - (NSString*)MIMEBoundary { - return kRKStringBoundary; + return kRKStringBoundary; } #pragma mark NSStream methods - (void)open { - // Generate the MIME header for this part - if (self.fileName && self.MIMEType) { - // Typical for file attachments - _MIMEHeader = [[[NSString stringWithFormat:@"--%@\r\nContent-Disposition: form-data; name=\"%@\"; " - @"filename=\"%@\"\r\nContent-Type: %@\r\n\r\n", - [self MIMEBoundary], self.name, self.fileName, self.MIMEType] dataUsingEncoding:NSUTF8StringEncoding] retain]; - } else if (self.MIMEType) { - // Typical for data values - _MIMEHeader = [[[NSString stringWithFormat:@"--%@\r\nContent-Disposition: form-data; name=\"%@\"\r\n" - @"Content-Type: %@\r\n\r\n", - [self MIMEBoundary], self.name, self.MIMEType] dataUsingEncoding:NSUTF8StringEncoding] retain]; - } else { - // Typical for raw values - _MIMEHeader = [[[NSString stringWithFormat:@"--%@\r\nContent-Disposition: form-data; name=\"%@\"\r\n\r\n", - [self MIMEBoundary], self.name] - dataUsingEncoding:NSUTF8StringEncoding] retain]; - } + // Generate the MIME header for this part + if (self.fileName && self.MIMEType) { + // Typical for file attachments + _MIMEHeader = [[[NSString stringWithFormat:@"--%@\r\nContent-Disposition: form-data; name=\"%@\"; " + @"filename=\"%@\"\r\nContent-Type: %@\r\n\r\n", + [self MIMEBoundary], self.name, self.fileName, self.MIMEType] dataUsingEncoding:NSUTF8StringEncoding] retain]; + } else if (self.MIMEType) { + // Typical for data values + _MIMEHeader = [[[NSString stringWithFormat:@"--%@\r\nContent-Disposition: form-data; name=\"%@\"\r\n" + @"Content-Type: %@\r\n\r\n", + [self MIMEBoundary], self.name, self.MIMEType] dataUsingEncoding:NSUTF8StringEncoding] retain]; + } else { + // Typical for raw values + _MIMEHeader = [[[NSString stringWithFormat:@"--%@\r\nContent-Disposition: form-data; name=\"%@\"\r\n\r\n", + [self MIMEBoundary], self.name] + dataUsingEncoding:NSUTF8StringEncoding] retain]; + } - // Calculate lengths - _MIMEHeaderLength = [_MIMEHeader length]; - _length = _MIMEHeaderLength + _bodyLength + 2; // \r\n is the + 2 + // Calculate lengths + _MIMEHeaderLength = [_MIMEHeader length]; + _length = _MIMEHeaderLength + _bodyLength + 2; // \r\n is the + 2 - // Open the stream + // Open the stream [_bodyStream open]; } @@ -160,19 +160,19 @@ extern NSString* const kRKStringBoundary; - (NSUInteger)read:(uint8_t *)buffer maxLength:(NSUInteger)maxLength { NSUInteger sent = 0, read; - // We are done with the read + // We are done with the read if (_delivered >= _length) { return 0; } - // First we send back the MIME headers + // First we send back the MIME headers if (_delivered < _MIMEHeaderLength && sent < maxLength) { - NSUInteger headerBytesRemaining, bytesRemainingInBuffer; + NSUInteger headerBytesRemaining, bytesRemainingInBuffer; - headerBytesRemaining = _MIMEHeaderLength - _delivered; - bytesRemainingInBuffer = maxLength; + headerBytesRemaining = _MIMEHeaderLength - _delivered; + bytesRemainingInBuffer = maxLength; - // Send the entire header if there is room + // Send the entire header if there is room read = (headerBytesRemaining < bytesRemainingInBuffer) ? headerBytesRemaining : bytesRemainingInBuffer; [_MIMEHeader getBytes:buffer range:NSMakeRange(_delivered, read)]; @@ -180,7 +180,7 @@ extern NSString* const kRKStringBoundary; _delivered += sent; } - // Read the attachment body out of our underlying stream + // Read the attachment body out of our underlying stream while (_delivered >= _MIMEHeaderLength && _delivered < (_length - 2) && sent < maxLength) { if ((read = [_bodyStream read:(buffer + sent) maxLength:(maxLength - sent)]) == 0) { break; @@ -190,17 +190,17 @@ extern NSString* const kRKStringBoundary; _delivered += read; } - // Append the \r\n + // Append the \r\n if (_delivered >= (_length - 2) && sent < maxLength) { if (_delivered == (_length - 2)) { *(buffer + sent) = '\r'; sent ++; - _delivered ++; + _delivered ++; } *(buffer + sent) = '\n'; sent ++; - _delivered ++; + _delivered ++; } return sent; diff --git a/Code/Network/RKReachabilityObserver.h b/Code/Network/RKReachabilityObserver.h index 41807083..390d71a8 100755 --- a/Code/Network/RKReachabilityObserver.h +++ b/Code/Network/RKReachabilityObserver.h @@ -45,20 +45,20 @@ typedef enum { /** Network reachability not yet known */ - RKReachabilityIndeterminate, + RKReachabilityIndeterminate, /** Network is not reachable */ - RKReachabilityNotReachable, + RKReachabilityNotReachable, /** Network is reachable via a WiFi connection */ - RKReachabilityReachableViaWiFi, + RKReachabilityReachableViaWiFi, /** Network is reachable via a "wireless wide area network" (WWAN). i.e. GPRS, Edge, 3G, etc. */ - RKReachabilityReachableViaWWAN + RKReachabilityReachableViaWWAN } RKReachabilityNetworkStatus; /** @@ -76,8 +76,8 @@ typedef enum { */ @interface RKReachabilityObserver : NSObject { NSString *_host; - SCNetworkReachabilityRef _reachabilityRef; - BOOL _reachabilityDetermined; + SCNetworkReachabilityRef _reachabilityRef; + BOOL _reachabilityDetermined; BOOL _monitoringLocalWiFi; SCNetworkReachabilityFlags _reachabilityFlags; } diff --git a/Code/Network/RKReachabilityObserver.m b/Code/Network/RKReachabilityObserver.m index 6d1d1be8..b2956f57 100755 --- a/Code/Network/RKReachabilityObserver.m +++ b/Code/Network/RKReachabilityObserver.m @@ -48,12 +48,12 @@ NSString* const RKReachabilityFlagsUserInfoKey = @"RKReachabilityFlagsUserInfoKe NSString* const RKReachabilityWasDeterminedNotification = @"RKReachabilityWasDeterminedNotification"; static void ReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkReachabilityFlags flags, void *info) { - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; + NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - RKReachabilityObserver *observer = (RKReachabilityObserver *) info; - observer.reachabilityFlags = flags; + RKReachabilityObserver *observer = (RKReachabilityObserver *) info; + observer.reachabilityFlags = flags; - [pool release]; + [pool release]; } #pragma mark - @@ -66,24 +66,24 @@ static void ReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkReach @synthesize monitoringLocalWiFi = _monitoringLocalWiFi; + (RKReachabilityObserver *)reachabilityObserverForAddress:(const struct sockaddr *)address { - return [[[self alloc] initWithAddress:address] autorelease]; + return [[[self alloc] initWithAddress:address] autorelease]; } + (RKReachabilityObserver *)reachabilityObserverForInternetAddress:(in_addr_t)internetAddress { - struct sockaddr_in address; - bzero(&address, sizeof(address)); - address.sin_len = sizeof(address); - address.sin_family = AF_INET; - address.sin_addr.s_addr = htonl(internetAddress); - return [self reachabilityObserverForAddress:(struct sockaddr *)&address]; + struct sockaddr_in address; + bzero(&address, sizeof(address)); + address.sin_len = sizeof(address); + address.sin_family = AF_INET; + address.sin_addr.s_addr = htonl(internetAddress); + return [self reachabilityObserverForAddress:(struct sockaddr *)&address]; } + (RKReachabilityObserver *)reachabilityObserverForInternet { - return [self reachabilityObserverForInternetAddress:INADDR_ANY]; + return [self reachabilityObserverForInternetAddress:INADDR_ANY]; } + (RKReachabilityObserver *)reachabilityObserverForLocalWifi { - return [self reachabilityObserverForInternetAddress:IN_LINKLOCALNETNUM]; + return [self reachabilityObserverForInternetAddress:IN_LINKLOCALNETNUM]; } + (RKReachabilityObserver *)reachabilityObserverForHost:(NSString *)hostNameOrIPAddress { @@ -92,19 +92,19 @@ static void ReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkReach - (id)initWithAddress:(const struct sockaddr *)address { self = [super init]; - if (self) { - _reachabilityRef = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, address); - if (_reachabilityRef == NULL) { + if (self) { + _reachabilityRef = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, address); + if (_reachabilityRef == NULL) { RKLogWarning(@"Unable to initialize reachability reference"); - [self release]; - self = nil; - } else { - // For technical details regarding link-local connections, please - // see the following source file at Apple's open-source site. - // - // http://www.opensource.apple.com/source/bootp/bootp-89/IPConfiguration.bproj/linklocal.c - // - _monitoringLocalWiFi = address->sa_len == sizeof(struct sockaddr_in) && address->sa_family == AF_INET && IN_LINKLOCAL(ntohl(((const struct sockaddr_in *)address)->sin_addr.s_addr)); + [self release]; + self = nil; + } else { + // For technical details regarding link-local connections, please + // see the following source file at Apple's open-source site. + // + // http://www.opensource.apple.com/source/bootp/bootp-89/IPConfiguration.bproj/linklocal.c + // + _monitoringLocalWiFi = address->sa_len == sizeof(struct sockaddr_in) && address->sa_family == AF_INET && IN_LINKLOCAL(ntohl(((const struct sockaddr_in *)address)->sin_addr.s_addr)); // Save the IP address char str[INET_ADDRSTRLEN]; @@ -125,9 +125,9 @@ static void ReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkReach // Schedule the observer [self scheduleObserver]; - } - } - return self; + } + } + return self; } - (id)initWithHost:(NSString *)hostNameOrIPAddress { @@ -155,9 +155,9 @@ static void ReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkReach RKLogInfo(@"Reachability observer initialized with hostname %@", hostNameOrIPAddress); if (_reachabilityRef == NULL) { RKLogWarning(@"Unable to initialize reachability reference"); - [self release]; - self = nil; - } else { + [self release]; + self = nil; + } else { [self scheduleObserver]; } } @@ -173,7 +173,7 @@ static void ReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkReach if (_reachabilityRef) { CFRelease(_reachabilityRef); } - [_host release]; + [_host release]; [super dealloc]; } @@ -229,59 +229,59 @@ static void ReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkReach } - (RKReachabilityNetworkStatus)networkStatus { - NSAssert(_reachabilityRef != NULL, @"currentNetworkStatus called with NULL reachabilityRef"); - RKReachabilityNetworkStatus status = RKReachabilityNotReachable; + NSAssert(_reachabilityRef != NULL, @"currentNetworkStatus called with NULL reachabilityRef"); + RKReachabilityNetworkStatus status = RKReachabilityNotReachable; - if (!self.reachabilityDetermined) { + if (!self.reachabilityDetermined) { RKLogTrace(@"Reachability observer %@ has not yet established reachability. networkStatus = %@", self, @"RKReachabilityIndeterminate"); - return RKReachabilityIndeterminate; - } + return RKReachabilityIndeterminate; + } RKLogTrace(@"Reachability Flags: %@\n", [self reachabilityFlagsDescription]); // If we are observing WiFi, we are only reachable via WiFi when flags are direct - if (self.isMonitoringLocalWiFi) { - if ((_reachabilityFlags & kSCNetworkReachabilityFlagsReachable) && (_reachabilityFlags & kSCNetworkReachabilityFlagsIsDirect)) { - // <-- reachable AND direct - status = RKReachabilityReachableViaWiFi; - } else { - // <-- NOT reachable OR NOT direct - status = RKReachabilityNotReachable; - } - } else { - if ((_reachabilityFlags & kSCNetworkReachabilityFlagsReachable)) { - // <-- reachable + if (self.isMonitoringLocalWiFi) { + if ((_reachabilityFlags & kSCNetworkReachabilityFlagsReachable) && (_reachabilityFlags & kSCNetworkReachabilityFlagsIsDirect)) { + // <-- reachable AND direct + status = RKReachabilityReachableViaWiFi; + } else { + // <-- NOT reachable OR NOT direct + status = RKReachabilityNotReachable; + } + } else { + if ((_reachabilityFlags & kSCNetworkReachabilityFlagsReachable)) { + // <-- reachable #if TARGET_OS_IPHONE - if ((_reachabilityFlags & kSCNetworkReachabilityFlagsIsWWAN)) { - // <-- reachable AND is wireless wide-area network (iOS only) - status = RKReachabilityReachableViaWWAN; - } else { + if ((_reachabilityFlags & kSCNetworkReachabilityFlagsIsWWAN)) { + // <-- reachable AND is wireless wide-area network (iOS only) + status = RKReachabilityReachableViaWWAN; + } else { #endif - // <-- reachable AND is NOT wireless wide-area network (iOS only) - if ((_reachabilityFlags & kSCNetworkReachabilityFlagsConnectionOnTraffic) || (_reachabilityFlags & kSCNetworkReachabilityFlagsConnectionOnDemand)) { - // <-- reachable, on-traffic OR on-demand connection - if ((_reachabilityFlags & kSCNetworkReachabilityFlagsInterventionRequired)) { - // <-- reachable, on-traffic OR on-demand connection, intervention required - status = (_reachabilityFlags & kSCNetworkReachabilityFlagsConnectionRequired) ? RKReachabilityNotReachable : RKReachabilityReachableViaWiFi; - } else { - // <-- reachable, on-traffic OR on-demand connection, intervention NOT required - status = RKReachabilityReachableViaWiFi; - } - } else { - // <-- reachable, NOT on-traffic OR on-demand connection - status = (_reachabilityFlags & kSCNetworkReachabilityFlagsConnectionRequired) ? RKReachabilityNotReachable : RKReachabilityReachableViaWiFi; - } + // <-- reachable AND is NOT wireless wide-area network (iOS only) + if ((_reachabilityFlags & kSCNetworkReachabilityFlagsConnectionOnTraffic) || (_reachabilityFlags & kSCNetworkReachabilityFlagsConnectionOnDemand)) { + // <-- reachable, on-traffic OR on-demand connection + if ((_reachabilityFlags & kSCNetworkReachabilityFlagsInterventionRequired)) { + // <-- reachable, on-traffic OR on-demand connection, intervention required + status = (_reachabilityFlags & kSCNetworkReachabilityFlagsConnectionRequired) ? RKReachabilityNotReachable : RKReachabilityReachableViaWiFi; + } else { + // <-- reachable, on-traffic OR on-demand connection, intervention NOT required + status = RKReachabilityReachableViaWiFi; + } + } else { + // <-- reachable, NOT on-traffic OR on-demand connection + status = (_reachabilityFlags & kSCNetworkReachabilityFlagsConnectionRequired) ? RKReachabilityNotReachable : RKReachabilityReachableViaWiFi; + } #if TARGET_OS_IPHONE - } + } #endif - } else { - // <-- NOT reachable - status = RKReachabilityNotReachable; - } - } + } else { + // <-- NOT reachable + status = RKReachabilityNotReachable; + } + } RKLogTrace(@"Reachability observer %@ determined networkStatus = %@", self, [self stringFromNetworkStatus:status]); - return status; + return status; } #pragma Reachability Flag Introspection @@ -295,15 +295,15 @@ static void ReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkReach [self validateIntrospection]; BOOL reachable = (RKReachabilityNotReachable != [self networkStatus]); RKLogDebug(@"Reachability observer %@ determined isNetworkReachable = %d", self, reachable); - return reachable; + return reachable; } - (BOOL)isConnectionRequired { - [self validateIntrospection]; + [self validateIntrospection]; BOOL required = (_reachabilityFlags & kSCNetworkReachabilityFlagsConnectionRequired); RKLogDebug(@"Reachability observer %@ determined isConnectionRequired = %d", self, required); - return required; + return required; } - (BOOL)isReachableViaWWAN { @@ -335,7 +335,7 @@ static void ReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkReach - (void)scheduleObserver { SCNetworkReachabilityContext context = { .info = self }; RKLogDebug(@"Scheduling reachability observer %@ in main dispatch queue", self); - if (! SCNetworkReachabilitySetCallback(_reachabilityRef, ReachabilityCallback, &context)) { + if (! SCNetworkReachabilitySetCallback(_reachabilityRef, ReachabilityCallback, &context)) { RKLogWarning(@"%@: SCNetworkReachabilitySetCallback() failed: %s", self, SCErrorString(SCError())); return; } @@ -347,13 +347,13 @@ static void ReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkReach } - (void)unscheduleObserver { - if (_reachabilityRef) { + if (_reachabilityRef) { RKLogDebug(@"%@: Unscheduling reachability observer from main dispatch queue", self); if (! SCNetworkReachabilitySetDispatchQueue(_reachabilityRef, NULL)) { - RKLogWarning("%@: SCNetworkReachabilitySetDispatchQueue() failed: %s\n", self, SCErrorString(SCError())); - return; - } - } else { + RKLogWarning("%@: SCNetworkReachabilitySetDispatchQueue() failed: %s\n", self, SCErrorString(SCError())); + return; + } + } else { RKLogDebug(@"%@: Failed to unschedule reachability observer %@: reachability reference is nil.", self, _reachabilityRef); } } diff --git a/Code/Network/RKRequest.m b/Code/Network/RKRequest.m index 20d4b276..7394d858 100644 --- a/Code/Network/RKRequest.m +++ b/Code/Network/RKRequest.m @@ -135,22 +135,22 @@ RKRequestMethod RKRequestMethodTypeFromName(NSString *methodName) { #endif + (RKRequest*)requestWithURL:(NSURL*)URL { - return [[[RKRequest alloc] initWithURL:URL] autorelease]; + return [[[RKRequest alloc] initWithURL:URL] autorelease]; } - (id)initWithURL:(NSURL*)URL { self = [self init]; - if (self) { - _URL = [URL retain]; + if (self) { + _URL = [URL retain]; [self reset]; _authenticationType = RKRequestAuthenticationTypeNone; - _cachePolicy = RKRequestCachePolicyDefault; + _cachePolicy = RKRequestCachePolicyDefault; _cacheTimeoutInterval = 0; _timeoutInterval = 120.0; _defaultHTTPEncoding = NSUTF8StringEncoding; _followRedirect = YES; - } - return self; + } + return self; } - (id)init { @@ -194,8 +194,8 @@ RKRequestMethod RKRequestMethodTypeFromName(NSString *methodName) { UIApplication* app = [UIApplication sharedApplication]; if ([app respondsToSelector:@selector(beginBackgroundTaskWithExpirationHandler:)]) { - [app endBackgroundTask:_backgroundTaskIdentifier]; - _backgroundTaskIdentifier = UIBackgroundTaskInvalid; + [app endBackgroundTask:_backgroundTaskIdentifier]; + _backgroundTaskIdentifier = UIBackgroundTaskInvalid; } #endif } @@ -203,31 +203,31 @@ RKRequestMethod RKRequestMethodTypeFromName(NSString *methodName) { - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; - self.delegate = nil; + self.delegate = nil; if (_onDidLoadResponse) Block_release(_onDidLoadResponse); if (_onDidFailLoadWithError) Block_release(_onDidFailLoadWithError); - _delegate = nil; + _delegate = nil; _configurationDelegate = nil; [_reachabilityObserver release]; _reachabilityObserver = nil; - [_connection cancel]; - [_connection release]; - _connection = nil; - [_userData release]; - _userData = nil; - [_URL release]; - _URL = nil; - [_URLRequest release]; - _URLRequest = nil; - [_params release]; - _params = nil; - [_additionalHTTPHeaders release]; - _additionalHTTPHeaders = nil; - [_username release]; - _username = nil; - [_password release]; - _password = nil; + [_connection cancel]; + [_connection release]; + _connection = nil; + [_userData release]; + _userData = nil; + [_URL release]; + _URL = nil; + [_URLRequest release]; + _URLRequest = nil; + [_params release]; + _params = nil; + [_additionalHTTPHeaders release]; + _additionalHTTPHeaders = nil; + [_username release]; + _username = nil; + [_password release]; + _password = nil; [_cache release]; _cache = nil; [_OAuth1ConsumerKey release]; @@ -263,16 +263,16 @@ RKRequestMethod RKRequestMethodTypeFromName(NSString *methodName) { } - (void)setRequestBody { - if ([self shouldSendParams]) { - // Prefer the use of a stream over a raw body - if ([_params respondsToSelector:@selector(HTTPBodyStream)]) { + if ([self shouldSendParams]) { + // Prefer the use of a stream over a raw body + if ([_params respondsToSelector:@selector(HTTPBodyStream)]) { // NOTE: This causes the stream to be retained. For RKParams, this will // cause a leak unless the stream is released. See [RKParams close] - [_URLRequest setHTTPBodyStream:[_params HTTPBodyStream]]; - } else { - [_URLRequest setHTTPBody:[_params HTTPBody]]; - } - } + [_URLRequest setHTTPBodyStream:[_params HTTPBodyStream]]; + } else { + [_URLRequest setHTTPBody:[_params HTTPBody]]; + } + } } - (NSData*)HTTPBody { @@ -292,22 +292,22 @@ RKRequestMethod RKRequestMethodTypeFromName(NSString *methodName) { } - (void)addHeadersToRequest { - NSString *header = nil; - for (header in _additionalHTTPHeaders) { - [_URLRequest setValue:[_additionalHTTPHeaders valueForKey:header] forHTTPHeaderField:header]; - } + NSString *header = nil; + for (header in _additionalHTTPHeaders) { + [_URLRequest setValue:[_additionalHTTPHeaders valueForKey:header] forHTTPHeaderField:header]; + } - if ([self shouldSendParams]) { - // Temporarily support older RKRequestSerializable implementations - if ([_params respondsToSelector:@selector(HTTPHeaderValueForContentType)]) { - [_URLRequest setValue:[_params HTTPHeaderValueForContentType] forHTTPHeaderField:@"Content-Type"]; - } else if ([_params respondsToSelector:@selector(ContentTypeHTTPHeader)]) { - [_URLRequest setValue:[_params performSelector:@selector(ContentTypeHTTPHeader)] forHTTPHeaderField:@"Content-Type"]; - } - if ([_params respondsToSelector:@selector(HTTPHeaderValueForContentLength)]) { - [_URLRequest setValue:[NSString stringWithFormat:@"%d", [_params HTTPHeaderValueForContentLength]] forHTTPHeaderField:@"Content-Length"]; - } - } else { + if ([self shouldSendParams]) { + // Temporarily support older RKRequestSerializable implementations + if ([_params respondsToSelector:@selector(HTTPHeaderValueForContentType)]) { + [_URLRequest setValue:[_params HTTPHeaderValueForContentType] forHTTPHeaderField:@"Content-Type"]; + } else if ([_params respondsToSelector:@selector(ContentTypeHTTPHeader)]) { + [_URLRequest setValue:[_params performSelector:@selector(ContentTypeHTTPHeader)] forHTTPHeaderField:@"Content-Type"]; + } + if ([_params respondsToSelector:@selector(HTTPHeaderValueForContentLength)]) { + [_URLRequest setValue:[NSString stringWithFormat:@"%d", [_params HTTPHeaderValueForContentLength]] forHTTPHeaderField:@"Content-Length"]; + } + } else { [_URLRequest setValue:@"0" forHTTPHeaderField:@"Content-Length"]; } @@ -386,14 +386,14 @@ RKRequestMethod RKRequestMethodTypeFromName(NSString *methodName) { // Setup the NSURLRequest. The request must be prepared right before dispatching - (BOOL)prepareURLRequest { - [_URLRequest setHTTPMethod:[self HTTPMethod]]; + [_URLRequest setHTTPMethod:[self HTTPMethod]]; if ([self.delegate respondsToSelector:@selector(requestWillPrepareForSend:)]) { [self.delegate requestWillPrepareForSend:self]; } - [self setRequestBody]; - [self addHeadersToRequest]; + [self setRequestBody]; + [self addHeadersToRequest]; NSString* body = [[NSString alloc] initWithData:[_URLRequest HTTPBody] encoding:NSUTF8StringEncoding]; RKLogTrace(@"Prepared %@ URLRequest '%@'. HTTP Headers: %@. HTTP Body: %@.", [self HTTPMethod], _URLRequest, [_URLRequest allHTTPHeaderFields], body); @@ -404,38 +404,38 @@ RKRequestMethod RKRequestMethodTypeFromName(NSString *methodName) { - (void)cancelAndInformDelegate:(BOOL)informDelegate { _cancelled = YES; - [_connection cancel]; - [_connection release]; - _connection = nil; + [_connection cancel]; + [_connection release]; + _connection = nil; [self invalidateTimeoutTimer]; - self.loading = NO; + self.loading = NO; - if (informDelegate && [_delegate respondsToSelector:@selector(requestDidCancelLoad:)]) { - [_delegate requestDidCancelLoad:self]; - } + if (informDelegate && [_delegate respondsToSelector:@selector(requestDidCancelLoad:)]) { + [_delegate requestDidCancelLoad:self]; + } } - (NSString*)HTTPMethod { - switch (_method) { - case RKRequestMethodGET: - return @"GET"; - break; - case RKRequestMethodPOST: - return @"POST"; - break; - case RKRequestMethodPUT: - return @"PUT"; - break; - case RKRequestMethodDELETE: - return @"DELETE"; - break; + switch (_method) { + case RKRequestMethodGET: + return @"GET"; + break; + case RKRequestMethodPOST: + return @"POST"; + break; + case RKRequestMethodPUT: + return @"PUT"; + break; + case RKRequestMethodDELETE: + return @"DELETE"; + break; case RKRequestMethodHEAD: - return @"HEAD"; - break; - default: - return nil; - break; - } + return @"HEAD"; + break; + default: + return nil; + break; + } } // NOTE: We could factor the knowledge about the queue out of RKRequest entirely, but it will break behavior. @@ -543,36 +543,36 @@ RKRequestMethod RKRequestMethodTypeFromName(NSString *methodName) { #else [self fireAsynchronousRequest]; #endif - } else { + } else { RKLogTrace(@"Declined to dispatch request %@: reachability observer reported the network is not available.", self); - if (_cachePolicy & RKRequestCachePolicyLoadIfOffline && - [self.cache hasResponseForRequest:self]) { - self.loading = YES; + if (_cachePolicy & RKRequestCachePolicyLoadIfOffline && + [self.cache hasResponseForRequest:self]) { + self.loading = YES; [self didFinishLoad:[self loadResponseFromCache]]; - } else { + } else { 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]]; - NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys: - errorMessage, NSLocalizedDescriptionKey, - nil]; + NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys: + errorMessage, NSLocalizedDescriptionKey, + nil]; NSError* error = [NSError errorWithDomain:RKErrorDomain code:RKRequestBaseURLOfflineError userInfo:userInfo]; [self performSelector:@selector(didFailLoadWithError:) withObject:error afterDelay:0]; } - } + } } - (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]) { + if ([self shouldLoadFromCache]) { response = [self loadResponseFromCache]; self.loading = YES; [self didFinishLoad:response]; @@ -584,9 +584,9 @@ RKRequestMethod RKRequestMethodTypeFromName(NSString *methodName) { return nil; } - [[NSNotificationCenter defaultCenter] postNotificationName:RKRequestSentNotification object:self userInfo:nil]; + [[NSNotificationCenter defaultCenter] postNotificationName:RKRequestSentNotification object:self userInfo:nil]; - self.loading = YES; + self.loading = YES; if ([self.delegate respondsToSelector:@selector(requestDidStartLoad:)]) { [self.delegate requestDidStartLoad:self]; } @@ -606,24 +606,24 @@ RKRequestMethod RKRequestMethodTypeFromName(NSString *methodName) { [self didFinishLoad:response]; } - } else { - if (_cachePolicy & RKRequestCachePolicyLoadIfOffline && - [self.cache hasResponseForRequest:self]) { + } else { + if (_cachePolicy & RKRequestCachePolicyLoadIfOffline && + [self.cache hasResponseForRequest:self]) { - response = [self loadResponseFromCache]; + response = [self loadResponseFromCache]; - } else { - NSString* errorMessage = [NSString stringWithFormat:@"The client is unable to contact the resource at %@", [[self URL] absoluteString]]; - NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys: - errorMessage, NSLocalizedDescriptionKey, - nil]; - error = [NSError errorWithDomain:RKErrorDomain code:RKRequestBaseURLOfflineError userInfo:userInfo]; - [self didFailLoadWithError:error]; - response = [[[RKResponse alloc] initWithSynchronousRequest:self URLResponse:URLResponse body:payload error:error] autorelease]; - } - } + } else { + NSString* errorMessage = [NSString stringWithFormat:@"The client is unable to contact the resource at %@", [[self URL] absoluteString]]; + NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys: + errorMessage, NSLocalizedDescriptionKey, + nil]; + error = [NSError errorWithDomain:RKErrorDomain code:RKRequestBaseURLOfflineError userInfo:userInfo]; + [self didFailLoadWithError:error]; + response = [[[RKResponse alloc] initWithSynchronousRequest:self URLResponse:URLResponse body:payload error:error] autorelease]; + } + } - return response; + return response; } - (void)cancel { @@ -651,17 +651,17 @@ RKRequestMethod RKRequestMethodTypeFromName(NSString *methodName) { } - (void)didFailLoadWithError:(NSError*)error { - if (_cachePolicy & RKRequestCachePolicyLoadOnError && - [self.cache hasResponseForRequest:self]) { + if (_cachePolicy & RKRequestCachePolicyLoadOnError && + [self.cache hasResponseForRequest:self]) { - [self didFinishLoad:[self loadResponseFromCache]]; - } else { + [self didFinishLoad:[self loadResponseFromCache]]; + } else { self.loaded = YES; self.loading = NO; - if ([_delegate respondsToSelector:@selector(request:didFailLoadWithError:)]) { - [_delegate request:self didFailLoadWithError:error]; - } + if ([_delegate respondsToSelector:@selector(request:didFailLoadWithError:)]) { + [_delegate request:self didFailLoadWithError:error]; + } if (self.onDidFailLoadWithError) { self.onDidFailLoadWithError(error); @@ -669,10 +669,10 @@ RKRequestMethod RKRequestMethodTypeFromName(NSString *methodName) { NSDictionary* userInfo = [NSDictionary dictionaryWithObject:error forKey:RKRequestDidFailWithErrorNotificationUserInfoErrorKey]; - [[NSNotificationCenter defaultCenter] postNotificationName:RKRequestDidFailWithErrorNotification + [[NSNotificationCenter defaultCenter] postNotificationName:RKRequestDidFailWithErrorNotification object:self userInfo:userInfo]; - } + } // NOTE: This notification must be posted last as the request queue releases the request when it // receives the notification @@ -686,26 +686,26 @@ RKRequestMethod RKRequestMethodTypeFromName(NSString *methodName) { } - (void)didFinishLoad:(RKResponse*)response { - self.loading = NO; - self.loaded = YES; + self.loading = NO; + self.loaded = YES; RKLogInfo(@"Status Code: %ld", (long) [response statusCode]); RKLogDebug(@"Body: %@", [response bodyAsString]); - RKResponse* finalResponse = response; + RKResponse* finalResponse = response; - if ((_cachePolicy & RKRequestCachePolicyEtag) && [response isNotModified]) { - finalResponse = [self loadResponseFromCache]; + if ((_cachePolicy & RKRequestCachePolicyEtag) && [response isNotModified]) { + finalResponse = [self loadResponseFromCache]; [self updateInternalCacheDate]; - } + } - if (![response wasLoadedFromCache] && [response isSuccessful] && (_cachePolicy != RKRequestCachePolicyNone)) { - [self.cache storeResponse:response forRequest:self]; - } + if (![response wasLoadedFromCache] && [response isSuccessful] && (_cachePolicy != RKRequestCachePolicyNone)) { + [self.cache storeResponse:response forRequest:self]; + } - if ([_delegate respondsToSelector:@selector(request:didLoadResponse:)]) { - [_delegate request:self didLoadResponse:finalResponse]; - } + if ([_delegate respondsToSelector:@selector(request:didLoadResponse:)]) { + [_delegate request:self didLoadResponse:finalResponse]; + } if (self.onDidLoadResponse) { self.onDidLoadResponse(finalResponse); @@ -728,23 +728,23 @@ RKRequestMethod RKRequestMethodTypeFromName(NSString *methodName) { } - (BOOL)isGET { - return _method == RKRequestMethodGET; + return _method == RKRequestMethodGET; } - (BOOL)isPOST { - return _method == RKRequestMethodPOST; + return _method == RKRequestMethodPOST; } - (BOOL)isPUT { - return _method == RKRequestMethodPUT; + return _method == RKRequestMethodPUT; } - (BOOL)isDELETE { - return _method == RKRequestMethodDELETE; + return _method == RKRequestMethodDELETE; } - (BOOL)isHEAD { - return _method == RKRequestMethodHEAD; + return _method == RKRequestMethodHEAD; } - (BOOL)isUnsent { @@ -752,12 +752,12 @@ RKRequestMethod RKRequestMethodTypeFromName(NSString *methodName) { } - (NSString*)resourcePath { - NSString* resourcePath = nil; - if ([self.URL isKindOfClass:[RKURL class]]) { - RKURL* url = (RKURL*)self.URL; - resourcePath = url.resourcePath; - } - return resourcePath; + NSString* resourcePath = nil; + if ([self.URL isKindOfClass:[RKURL class]]) { + RKURL* url = (RKURL*)self.URL; + resourcePath = url.resourcePath; + } + return resourcePath; } - (void)setURL:(NSURL *)URL { @@ -770,13 +770,13 @@ RKRequestMethod RKRequestMethodTypeFromName(NSString *methodName) { - (void)setResourcePath:(NSString *)resourcePath { if ([self.URL isKindOfClass:[RKURL class]]) { self.URL = [(RKURL *)self.URL URLByReplacingResourcePath:resourcePath]; - } else { + } else { self.URL = [RKURL URLWithBaseURL:self.URL resourcePath:resourcePath]; } } - (BOOL)wasSentToResourcePath:(NSString*)resourcePath { - return [[self resourcePath] isEqualToString:resourcePath]; + return [[self resourcePath] isEqualToString:resourcePath]; } - (BOOL)wasSentToResourcePath:(NSString *)resourcePath method:(RKRequestMethod)method { @@ -836,15 +836,15 @@ RKRequestMethod RKRequestMethodTypeFromName(NSString *methodName) { // Deprecations + (RKRequest*)requestWithURL:(NSURL*)URL delegate:(id)delegate { - return [[[RKRequest alloc] initWithURL:URL delegate:delegate] autorelease]; + return [[[RKRequest alloc] initWithURL:URL delegate:delegate] autorelease]; } - (id)initWithURL:(NSURL*)URL delegate:(id)delegate { self = [self initWithURL:URL]; - if (self) { - _delegate = delegate; - } - return self; + if (self) { + _delegate = delegate; + } + return self; } @end diff --git a/Code/Network/RKRequestCache.m b/Code/Network/RKRequestCache.m index 94e8bc57..d0d376ed 100644 --- a/Code/Network/RKRequestCache.m +++ b/Code/Network/RKRequestCache.m @@ -40,39 +40,39 @@ static NSDateFormatter* __rfc1123DateFormatter; @synthesize storagePolicy = _storagePolicy; + (NSDateFormatter*)rfc1123DateFormatter { - if (__rfc1123DateFormatter == nil) { - __rfc1123DateFormatter = [[NSDateFormatter alloc] init]; - [__rfc1123DateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; - [__rfc1123DateFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss 'GMT'"]; - } - return __rfc1123DateFormatter; + if (__rfc1123DateFormatter == nil) { + __rfc1123DateFormatter = [[NSDateFormatter alloc] init]; + [__rfc1123DateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; + [__rfc1123DateFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss 'GMT'"]; + } + return __rfc1123DateFormatter; } - (id)initWithPath:(NSString*)cachePath storagePolicy:(RKRequestCacheStoragePolicy)storagePolicy { self = [super init]; - if (self) { + if (self) { _cache = [[RKCache alloc] initWithPath:cachePath subDirectories: [NSArray arrayWithObjects:RKRequestCacheSessionCacheDirectory, RKRequestCachePermanentCacheDirectory, nil]]; - self.storagePolicy = storagePolicy; - } + self.storagePolicy = storagePolicy; + } - return self; + return self; } - (void)dealloc { - [_cache release]; - _cache = nil; - [super dealloc]; + [_cache release]; + _cache = nil; + [super dealloc]; } - (NSString*)path { - return _cache.cachePath; + return _cache.cachePath; } - (NSString*)pathForRequest:(RKRequest*)request { - NSString* pathForRequest = nil; + NSString* pathForRequest = nil; NSString* requestCacheKey = [request cacheKey]; if (requestCacheKey) { if (_storagePolicy == RKRequestCacheStoragePolicyForDurationOfSession) { @@ -85,69 +85,69 @@ static NSDateFormatter* __rfc1123DateFormatter; } else { RKLogTrace(@"Failed to find cacheKey for %@ due to nil cacheKey", request); } - return pathForRequest; + return pathForRequest; } - (BOOL)hasResponseForRequest:(RKRequest*)request { - BOOL hasEntryForRequest = NO; - NSString* cacheKey = [self pathForRequest:request]; + BOOL hasEntryForRequest = NO; + NSString* cacheKey = [self pathForRequest:request]; if (cacheKey) { hasEntryForRequest = ([_cache hasEntry:cacheKey] && [_cache hasEntry:[cacheKey stringByAppendingPathExtension:RKRequestCacheHeadersExtension]]); } RKLogTrace(@"Determined hasResponseForRequest: %@ => %@", request, hasEntryForRequest ? @"YES" : @"NO"); - return hasEntryForRequest; + return hasEntryForRequest; } - (void)storeResponse:(RKResponse*)response forRequest:(RKRequest*)request { - if ([self hasResponseForRequest:request]) { - [self invalidateRequest:request]; - } + if ([self hasResponseForRequest:request]) { + [self invalidateRequest:request]; + } - if (_storagePolicy != RKRequestCacheStoragePolicyDisabled) { - NSString* cacheKey = [self pathForRequest:request]; - if (cacheKey) { + if (_storagePolicy != RKRequestCacheStoragePolicyDisabled) { + NSString* cacheKey = [self pathForRequest:request]; + if (cacheKey) { [_cache writeData:response.body withCacheKey:cacheKey]; - NSMutableDictionary* headers = [response.allHeaderFields mutableCopy]; - if (headers) { + NSMutableDictionary* headers = [response.allHeaderFields mutableCopy]; + if (headers) { // TODO: expose this? NSHTTPURLResponse* urlResponse = [response valueForKey:@"_httpURLResponse"]; // Cache Loaded Time - [headers setObject:[[RKRequestCache rfc1123DateFormatter] stringFromDate:[NSDate date]] - forKey:RKRequestCacheDateHeaderKey]; + [headers setObject:[[RKRequestCache rfc1123DateFormatter] stringFromDate:[NSDate date]] + forKey:RKRequestCacheDateHeaderKey]; // Cache status code [headers setObject:[NSNumber numberWithInteger:urlResponse.statusCode] - forKey:RKRequestCacheStatusCodeHeadersKey]; + forKey:RKRequestCacheStatusCodeHeadersKey]; // Cache MIME Type [headers setObject:urlResponse.MIMEType - forKey:RKRequestCacheMIMETypeHeadersKey]; + forKey:RKRequestCacheMIMETypeHeadersKey]; // Cache URL [headers setObject:[urlResponse.URL absoluteString] - forKey:RKRequestCacheURLHeadersKey]; + forKey:RKRequestCacheURLHeadersKey]; // Save [_cache writeDictionary:headers withCacheKey:[cacheKey stringByAppendingPathExtension:RKRequestCacheHeadersExtension]]; - } - [headers release]; - } - } + } + [headers release]; + } + } } - (RKResponse*)responseForRequest:(RKRequest*)request { - RKResponse* response = nil; - NSString* cacheKey = [self pathForRequest:request]; - if (cacheKey) { - NSData* responseData = [_cache dataForCacheKey:cacheKey]; + RKResponse* response = nil; + NSString* cacheKey = [self pathForRequest:request]; + if (cacheKey) { + NSData* responseData = [_cache dataForCacheKey:cacheKey]; NSDictionary* responseHeaders = [_cache dictionaryForCacheKey:[cacheKey stringByAppendingPathExtension:RKRequestCacheHeadersExtension]]; - response = [[[RKResponse alloc] initWithRequest:request body:responseData headers:responseHeaders] autorelease]; - } + response = [[[RKResponse alloc] initWithRequest:request body:responseData headers:responseHeaders] autorelease]; + } RKLogDebug(@"Found cached RKResponse '%@' for '%@'", response, request); - return response; + return response; } - (NSDictionary*)headersForRequest:(RKRequest*)request { NSDictionary* headers = nil; - NSString* cacheKey = [self pathForRequest:request]; + NSString* cacheKey = [self pathForRequest:request]; if (cacheKey) { NSString* headersCacheKey = [cacheKey stringByAppendingPathExtension:RKRequestCacheHeadersExtension]; headers = [_cache dictionaryForCacheKey:headersCacheKey]; @@ -163,7 +163,7 @@ static NSDateFormatter* __rfc1123DateFormatter; } - (NSString*)etagForRequest:(RKRequest*)request { - NSString* etag = nil; + NSString* etag = nil; NSDictionary* responseHeaders = [self headersForRequest:request]; if (responseHeaders) { @@ -174,11 +174,11 @@ static NSDateFormatter* __rfc1123DateFormatter; } } RKLogDebug(@"Found cached ETag '%@' for '%@'", etag, request); - return etag; + return etag; } - (void)setCacheDate:(NSDate*)date forRequest:(RKRequest*)request { - NSString* cacheKey = [self pathForRequest:request]; + NSString* cacheKey = [self pathForRequest:request]; if (cacheKey) { NSMutableDictionary* responseHeaders = [[self headersForRequest:request] mutableCopy]; @@ -191,7 +191,7 @@ static NSDateFormatter* __rfc1123DateFormatter; } - (NSDate*)cacheDateForRequest:(RKRequest*)request { - NSDate* date = nil; + NSDate* date = nil; NSString* dateString = nil; NSDictionary* responseHeaders = [self headersForRequest:request]; @@ -204,27 +204,27 @@ static NSDateFormatter* __rfc1123DateFormatter; } date = [[RKRequestCache rfc1123DateFormatter] dateFromString:dateString]; RKLogDebug(@"Found cached date '%@' for '%@'", date, request); - return date; + return date; } - (void)invalidateRequest:(RKRequest*)request { RKLogDebug(@"Invalidating cache entry for '%@'", request); - NSString* cacheKey = [self pathForRequest:request]; - if (cacheKey) { + NSString* cacheKey = [self pathForRequest:request]; + if (cacheKey) { [_cache invalidateEntry:cacheKey]; [_cache invalidateEntry:[cacheKey stringByAppendingPathExtension:RKRequestCacheHeadersExtension]]; RKLogTrace(@"Removed cache entry at path '%@' for '%@'", cacheKey, request); - } + } } - (void)invalidateWithStoragePolicy:(RKRequestCacheStoragePolicy)storagePolicy { - if (storagePolicy != RKRequestCacheStoragePolicyDisabled) { - if (storagePolicy == RKRequestCacheStoragePolicyForDurationOfSession) { + if (storagePolicy != RKRequestCacheStoragePolicyDisabled) { + if (storagePolicy == RKRequestCacheStoragePolicyForDurationOfSession) { [_cache invalidateSubDirectory:RKRequestCacheSessionCacheDirectory]; - } else { + } else { [_cache invalidateSubDirectory:RKRequestCachePermanentCacheDirectory]; - } - } + } + } } - (void)invalidateAll { @@ -234,11 +234,11 @@ static NSDateFormatter* __rfc1123DateFormatter; } - (void)setStoragePolicy:(RKRequestCacheStoragePolicy)storagePolicy { - [self invalidateWithStoragePolicy:RKRequestCacheStoragePolicyForDurationOfSession]; - if (storagePolicy == RKRequestCacheStoragePolicyDisabled) { - [self invalidateWithStoragePolicy:RKRequestCacheStoragePolicyPermanently]; - } - _storagePolicy = storagePolicy; + [self invalidateWithStoragePolicy:RKRequestCacheStoragePolicyForDurationOfSession]; + if (storagePolicy == RKRequestCacheStoragePolicyDisabled) { + [self invalidateWithStoragePolicy:RKRequestCacheStoragePolicyPermanently]; + } + _storagePolicy = storagePolicy; } @end diff --git a/Code/Network/RKRequestQueue.m b/Code/Network/RKRequestQueue.m index 9ddbd5d4..fee75e9f 100644 --- a/Code/Network/RKRequestQueue.m +++ b/Code/Network/RKRequestQueue.m @@ -130,12 +130,12 @@ static const NSTimeInterval kFlushDelay = 0.3; } - (id)init { - if ((self = [super init])) { - _requests = [[NSMutableArray alloc] init]; + if ((self = [super init])) { + _requests = [[NSMutableArray alloc] init]; _loadingRequests = [[NSMutableSet alloc] init]; - _suspended = YES; - _concurrentRequestsLimit = 5; - _requestTimeout = 300; + _suspended = YES; + _concurrentRequestsLimit = 5; + _requestTimeout = 300; _showsNetworkActivityIndicatorWhenBusy = NO; #if TARGET_OS_IPHONE @@ -151,8 +151,8 @@ static const NSTimeInterval kFlushDelay = 0.3; object:nil]; } #endif - } - return self; + } + return self; } - (void)removeFromNamedQueues { @@ -239,14 +239,14 @@ static const NSTimeInterval kFlushDelay = 0.3; } - (void)loadNextInQueueDelayed { - if (!_queueTimer) { - _queueTimer = [NSTimer scheduledTimerWithTimeInterval:kFlushDelay - target:self - selector:@selector(loadNextInQueue) - userInfo:nil - repeats:NO]; + if (!_queueTimer) { + _queueTimer = [NSTimer scheduledTimerWithTimeInterval:kFlushDelay + target:self + selector:@selector(loadNextInQueue) + userInfo:nil + repeats:NO]; RKLogTrace(@"Timer initialized with delay %f for queue %@", kFlushDelay, self); - } + } } - (RKRequest*)nextRequest { @@ -268,17 +268,17 @@ static const NSTimeInterval kFlushDelay = 0.3; return; } - // Make sure that the Request Queue does not fire off any requests until the Reachability state has been determined. - if (self.suspended) { - _queueTimer = nil; - [self loadNextInQueueDelayed]; + // Make sure that the Request Queue does not fire off any requests until the Reachability state has been determined. + if (self.suspended) { + _queueTimer = nil; + [self loadNextInQueueDelayed]; RKLogTrace(@"Deferring request loading for queue %@ due to suspension", self); - return; - } + return; + } - NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; - _queueTimer = nil; + NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + _queueTimer = nil; @synchronized(self) { RKRequest* request = [self nextRequest]; @@ -300,11 +300,11 @@ static const NSTimeInterval kFlushDelay = 0.3; } } - if (_requests.count && !_suspended) { - [self loadNextInQueueDelayed]; - } + if (_requests.count && !_suspended) { + [self loadNextInQueueDelayed]; + } - [pool drain]; + [pool drain]; } - (void)setSuspended:(BOOL)isSuspended { @@ -326,14 +326,14 @@ static const NSTimeInterval kFlushDelay = 0.3; } } - _suspended = isSuspended; + _suspended = isSuspended; - if (!_suspended) { - [self loadNextInQueue]; - } else if (_queueTimer) { - [_queueTimer invalidate]; - _queueTimer = nil; - } + if (!_suspended) { + [self loadNextInQueue]; + } else if (_queueTimer) { + [_queueTimer invalidate]; + _queueTimer = nil; + } } - (void)addRequest:(RKRequest*)request { @@ -358,7 +358,7 @@ static const NSTimeInterval kFlushDelay = 0.3; name:RKRequestDidFailWithErrorNotification object:request]; - [self loadNextInQueue]; + [self loadNextInQueue]; } - (BOOL)removeRequest:(RKRequest*)request { @@ -400,8 +400,8 @@ static const NSTimeInterval kFlushDelay = 0.3; } else if ([self containsRequest:request] && [request isLoading]) { RKLogDebug(@"Canceled loading request %@ and removed from queue %@", request, self); - [request cancel]; - request.delegate = nil; + [request cancel]; + request.delegate = nil; if ([_delegate respondsToSelector:@selector(requestQueue:didCancelRequest:)]) { [_delegate requestQueue:self didCancelRequest:request]; @@ -409,52 +409,52 @@ static const NSTimeInterval kFlushDelay = 0.3; [self removeRequest:request]; - if (loadNext) { - [self loadNextInQueue]; - } - } + if (loadNext) { + [self loadNextInQueue]; + } + } } - (void)cancelRequest:(RKRequest*)request { - [self cancelRequest:request loadNext:YES]; + [self cancelRequest:request loadNext:YES]; } - (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) { - if (request.delegate && request.delegate == delegate) { - [self cancelRequest:request]; - } - } - [pool drain]; + NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + NSArray* requestsCopy = [NSArray arrayWithArray:_requests]; + for (RKRequest* request in requestsCopy) { + if (request.delegate && request.delegate == delegate) { + [self cancelRequest:request]; + } + } + [pool drain]; } - (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) { - if (request.delegate && request.delegate == delegate) { + 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]; - } - } - [pool drain]; + [self cancelRequest:request]; + } + } + [pool drain]; } - (void)cancelAllRequests { RKLogDebug(@"Cancelling all request in queue %@", self); - NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; - NSArray* requestsCopy = [NSArray arrayWithArray:_requests]; - for (RKRequest* request in requestsCopy) { - [self cancelRequest:request loadNext:NO]; - } - [pool drain]; + NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; + NSArray* requestsCopy = [NSArray arrayWithArray:_requests]; + for (RKRequest* request in requestsCopy) { + [self cancelRequest:request loadNext:NO]; + } + [pool drain]; } - (void)start { @@ -464,7 +464,7 @@ static const NSTimeInterval kFlushDelay = 0.3; - (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); + RKLogTrace(@"Received notification: %@", notification); RKRequest* request = (RKRequest*)notification.object; NSDictionary* userInfo = [notification userInfo]; @@ -483,7 +483,7 @@ static const NSTimeInterval kFlushDelay = 0.3; - (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); + RKLogTrace(@"Received notification: %@", notification); RKRequest* request = (RKRequest*)notification.object; NSDictionary* userInfo = [notification userInfo]; @@ -512,7 +512,7 @@ static const NSTimeInterval kFlushDelay = 0.3; */ - (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); + RKLogTrace(@"Received notification: %@", notification); RKRequest* request = (RKRequest*)notification.object; if ([self containsRequest:request]) { diff --git a/Code/Network/RKResponse.h b/Code/Network/RKResponse.h index 6d81d44f..0719327f 100644 --- a/Code/Network/RKResponse.h +++ b/Code/Network/RKResponse.h @@ -25,12 +25,12 @@ 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; + 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 21ac3da4..0f9c13ce 100644 --- a/Code/Network/RKResponse.m +++ b/Code/Network/RKResponse.m @@ -40,62 +40,62 @@ return __VA_ARGS__; - (id)init { self = [super init]; - if (self) { - _body = [[NSMutableData alloc] init]; - _failureError = nil; - _loading = NO; - _responseHeaders = nil; - } + if (self) { + _body = [[NSMutableData alloc] init]; + _failureError = nil; + _loading = NO; + _responseHeaders = nil; + } - return self; + return self; } - (id)initWithRequest:(RKRequest*)request { self = [self init]; - if (self) { - // We don't retain here as we're letting RKRequestQueue manage - // request ownership - _request = request; - } + if (self) { + // We don't retain here as we're letting RKRequestQueue manage + // request ownership + _request = request; + } - return self; + return self; } - (id)initWithRequest:(RKRequest*)request body:(NSData*)body headers:(NSDictionary*)headers { - self = [self initWithRequest:request]; - if (self) { - [_body release]; + self = [self initWithRequest:request]; + if (self) { + [_body release]; _body = [[NSMutableData dataWithData:body] retain]; - _responseHeaders = [headers retain]; - } + _responseHeaders = [headers retain]; + } - return self; + return self; } - (id)initWithSynchronousRequest:(RKRequest*)request URLResponse:(NSHTTPURLResponse*)URLResponse body:(NSData*)body error:(NSError*)error { self = [super init]; - if (self) { - _request = request; - _httpURLResponse = [URLResponse retain]; - _failureError = [error retain]; + if (self) { + _request = request; + _httpURLResponse = [URLResponse retain]; + _failureError = [error retain]; _body = [[NSMutableData dataWithData:body] retain]; - _loading = NO; - } + _loading = NO; + } - return self; + return self; } - (void)dealloc { _request = nil; - [_httpURLResponse release]; - _httpURLResponse = nil; - [_body release]; - _body = nil; - [_failureError release]; - _failureError = nil; - [_responseHeaders release]; - _responseHeaders = nil; - [super dealloc]; + [_httpURLResponse release]; + _httpURLResponse = nil; + [_body release]; + _body = nil; + [_failureError release]; + _failureError = nil; + [_responseHeaders release]; + _responseHeaders = nil; + [super dealloc]; } - (BOOL)hasCredentials { @@ -136,41 +136,41 @@ return __VA_ARGS__; RKResponseIgnoreDelegateIfCancelled(); RKLogDebug(@"Received authentication challenge"); - if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { - SecTrustRef trust = [[challenge protectionSpace] serverTrust]; - if ([self isServerTrusted:trust]) { - [challenge.sender useCredential:[NSURLCredential credentialForTrust:trust] forAuthenticationChallenge:challenge]; - } else { - [[challenge sender] cancelAuthenticationChallenge:challenge]; - } - return; - } + if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { + SecTrustRef trust = [[challenge protectionSpace] serverTrust]; + if ([self isServerTrusted:trust]) { + [challenge.sender useCredential:[NSURLCredential credentialForTrust:trust] forAuthenticationChallenge:challenge]; + } else { + [[challenge sender] cancelAuthenticationChallenge:challenge]; + } + return; + } - if ([challenge previousFailureCount] == 0) { - NSURLCredential *newCredential; - newCredential=[NSURLCredential credentialWithUser:[NSString stringWithFormat:@"%@", _request.username] - password:[NSString stringWithFormat:@"%@", _request.password] + if ([challenge previousFailureCount] == 0) { + NSURLCredential *newCredential; + 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]); - [[challenge sender] cancelAuthenticationChallenge:challenge]; - } + [[challenge sender] useCredential:newCredential + forAuthenticationChallenge:challenge]; + } else { + RKLogWarning(@"Failed authentication challenge after %ld failures", (long) [challenge previousFailureCount]); + [[challenge sender] cancelAuthenticationChallenge:challenge]; + } } - (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)space { RKResponseIgnoreDelegateIfCancelled(NO); RKLogDebug(@"Asked if canAuthenticateAgainstProtectionSpace: with authenticationMethod = %@", [space authenticationMethod]); - if ([[space authenticationMethod] isEqualToString:NSURLAuthenticationMethodServerTrust]) { - // server is using an SSL certificate that the OS can't validate - // see whether the client settings allow validation here - if (_request.disableCertificateValidation || [_request.additionalRootCertificates count] > 0) { - return YES; - } else { - return NO; - } - } + if ([[space authenticationMethod] isEqualToString:NSURLAuthenticationMethodServerTrust]) { + // server is using an SSL certificate that the OS can't validate + // see whether the client settings allow validation here + if (_request.disableCertificateValidation || [_request.additionalRootCertificates count] > 0) { + return YES; + } else { + return NO; + } + } // Handle non-SSL challenges BOOL hasCredentials = [self hasCredentials]; @@ -193,7 +193,7 @@ return __VA_ARGS__; - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { RKResponseIgnoreDelegateIfCancelled(); - [_body appendData:data]; + [_body appendData:data]; [_request invalidateTimeoutTimer]; if ([[_request delegate] respondsToSelector:@selector(request:didReceiveData:totalBytesReceived:totalBytesExpectedToReceive:)]) { [[_request delegate] request:_request didReceiveData:[data length] totalBytesReceived:[_body length] totalBytesExpectedToReceive:_httpURLResponse.expectedContentLength]; @@ -204,7 +204,7 @@ return __VA_ARGS__; RKResponseIgnoreDelegateIfCancelled(); RKLogDebug(@"NSHTTPURLResponse Status Code: %ld", (long) [response statusCode]); RKLogDebug(@"Headers: %@", [response allHeaderFields]); - _httpURLResponse = [response retain]; + _httpURLResponse = [response retain]; [_request invalidateTimeoutTimer]; if ([[_request delegate] respondsToSelector:@selector(request:didReceiveResponse:)]) { [[_request delegate] request:_request didReceiveResponse:self]; @@ -213,8 +213,8 @@ return __VA_ARGS__; - (void)connectionDidFinishLoading:(NSURLConnection *)connection { RKResponseIgnoreDelegateIfCancelled(); - RKLogTrace(@"Read response body: %@", [self bodyAsString]); - [_request didFinishLoad:self]; + RKLogTrace(@"Read response body: %@", [self bodyAsString]); + [_request didFinishLoad:self]; } - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { @@ -240,17 +240,17 @@ return __VA_ARGS__; RKResponseIgnoreDelegateIfCancelled(); [_request invalidateTimeoutTimer]; - if ([[_request delegate] respondsToSelector:@selector(request:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite:)]) { - [[_request delegate] request:_request didSendBodyData:bytesWritten totalBytesWritten:totalBytesWritten totalBytesExpectedToWrite:totalBytesExpectedToWrite]; - } + if ([[_request delegate] respondsToSelector:@selector(request:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite:)]) { + [[_request delegate] request:_request didSendBodyData:bytesWritten totalBytesWritten:totalBytesWritten totalBytesExpectedToWrite:totalBytesExpectedToWrite]; + } } - (NSString*)localizedStatusCodeString { - return [NSHTTPURLResponse localizedStringForStatusCode:[self statusCode]]; + return [NSHTTPURLResponse localizedStringForStatusCode:[self statusCode]]; } - (NSData *)body { - return _body; + return _body; } - (NSString *)bodyEncodingName { @@ -267,7 +267,7 @@ return __VA_ARGS__; } - (NSString *)bodyAsString { - return [[[NSString alloc] initWithData:self.body encoding:[self bodyEncoding]] autorelease]; + return [[[NSString alloc] initWithData:self.body encoding:[self bodyEncoding]] autorelease]; } - (id)bodyAsJSON { @@ -292,29 +292,29 @@ return __VA_ARGS__; } - (NSString*)failureErrorDescription { - if ([self isFailure]) { - return [_failureError localizedDescription]; - } else { - return nil; - } + if ([self isFailure]) { + return [_failureError localizedDescription]; + } else { + return nil; + } } - (BOOL)wasLoadedFromCache { - return (_responseHeaders != nil); + return (_responseHeaders != nil); } - (NSURL*)URL { if ([self wasLoadedFromCache]) { return [NSURL URLWithString:[_responseHeaders valueForKey:RKRequestCacheURLHeadersKey]]; } - return [_httpURLResponse URL]; + return [_httpURLResponse URL]; } - (NSString*)MIMEType { if ([self wasLoadedFromCache]) { return [_responseHeaders valueForKey:RKRequestCacheMIMETypeHeadersKey]; } - return [_httpURLResponse MIMEType]; + return [_httpURLResponse MIMEType]; } - (NSInteger)statusCode { @@ -325,74 +325,74 @@ return __VA_ARGS__; } - (NSDictionary*)allHeaderFields { - if ([self wasLoadedFromCache]) { - return _responseHeaders; - } + if ([self wasLoadedFromCache]) { + return _responseHeaders; + } return ([_httpURLResponse respondsToSelector:@selector(allHeaderFields)] ? [_httpURLResponse allHeaderFields] : nil); } - (NSArray*)cookies { - return [NSHTTPCookie cookiesWithResponseHeaderFields:self.allHeaderFields forURL:self.URL]; + return [NSHTTPCookie cookiesWithResponseHeaderFields:self.allHeaderFields forURL:self.URL]; } - (BOOL)isFailure { - return (nil != _failureError); + return (nil != _failureError); } - (BOOL)isInvalid { - return ([self statusCode] < 100 || [self statusCode] > 600); + return ([self statusCode] < 100 || [self statusCode] > 600); } - (BOOL)isInformational { - return ([self statusCode] >= 100 && [self statusCode] < 200); + return ([self statusCode] >= 100 && [self statusCode] < 200); } - (BOOL)isSuccessful { - return (([self statusCode] >= 200 && [self statusCode] < 300) || ([self wasLoadedFromCache])); + return (([self statusCode] >= 200 && [self statusCode] < 300) || ([self wasLoadedFromCache])); } - (BOOL)isRedirection { - return ([self statusCode] >= 300 && [self statusCode] < 400); + return ([self statusCode] >= 300 && [self statusCode] < 400); } - (BOOL)isClientError { - return ([self statusCode] >= 400 && [self statusCode] < 500); + return ([self statusCode] >= 400 && [self statusCode] < 500); } - (BOOL)isServerError { - return ([self statusCode] >= 500 && [self statusCode] < 600); + return ([self statusCode] >= 500 && [self statusCode] < 600); } - (BOOL)isError { - return ([self isClientError] || [self isServerError]); + return ([self isClientError] || [self isServerError]); } - (BOOL)isOK { - return ([self statusCode] == 200); + return ([self statusCode] == 200); } - (BOOL)isCreated { - return ([self statusCode] == 201); + return ([self statusCode] == 201); } - (BOOL)isNoContent { - return ([self statusCode] == 204); + return ([self statusCode] == 204); } - (BOOL)isNotModified { - return ([self statusCode] == 304); + return ([self statusCode] == 304); } - (BOOL)isUnauthorized { - return ([self statusCode] == 401); + return ([self statusCode] == 401); } - (BOOL)isForbidden { - return ([self statusCode] == 403); + return ([self statusCode] == 403); } - (BOOL)isNotFound { - return ([self statusCode] == 404); + return ([self statusCode] == 404); } - (BOOL)isConflict { @@ -404,59 +404,59 @@ return __VA_ARGS__; } - (BOOL)isUnprocessableEntity { - return ([self statusCode] == 422); + return ([self statusCode] == 422); } - (BOOL)isRedirect { - return ([self statusCode] == 301 || [self statusCode] == 302 || [self statusCode] == 303 || [self statusCode] == 307); + return ([self statusCode] == 301 || [self statusCode] == 302 || [self statusCode] == 303 || [self statusCode] == 307); } - (BOOL)isEmpty { - return ([self statusCode] == 201 || [self statusCode] == 204 || [self statusCode] == 304); + return ([self statusCode] == 201 || [self statusCode] == 204 || [self statusCode] == 304); } - (BOOL)isServiceUnavailable { - return ([self statusCode] == 503); + return ([self statusCode] == 503); } - (NSString*)contentType { - return ([[self allHeaderFields] objectForKey:@"Content-Type"]); + return ([[self allHeaderFields] objectForKey:@"Content-Type"]); } - (NSString*)contentLength { - return ([[self allHeaderFields] objectForKey:@"Content-Length"]); + return ([[self allHeaderFields] objectForKey:@"Content-Length"]); } - (NSString*)location { - return ([[self allHeaderFields] objectForKey:@"Location"]); + return ([[self allHeaderFields] objectForKey:@"Location"]); } - (BOOL)isHTML { - NSString* contentType = [self contentType]; - return (contentType && ([contentType rangeOfString:@"text/html" - options:NSCaseInsensitiveSearch|NSAnchoredSearch].length > 0 || - [self isXHTML])); + NSString* contentType = [self contentType]; + return (contentType && ([contentType rangeOfString:@"text/html" + options:NSCaseInsensitiveSearch|NSAnchoredSearch].length > 0 || + [self isXHTML])); } - (BOOL)isXHTML { - NSString* contentType = [self contentType]; - return (contentType && - [contentType rangeOfString:@"application/xhtml+xml" - options:NSCaseInsensitiveSearch|NSAnchoredSearch].length > 0); + NSString* contentType = [self contentType]; + return (contentType && + [contentType rangeOfString:@"application/xhtml+xml" + options:NSCaseInsensitiveSearch|NSAnchoredSearch].length > 0); } - (BOOL)isXML { - NSString* contentType = [self contentType]; - return (contentType && - [contentType rangeOfString:@"application/xml" - options:NSCaseInsensitiveSearch|NSAnchoredSearch].length > 0); + NSString* contentType = [self contentType]; + return (contentType && + [contentType rangeOfString:@"application/xml" + options:NSCaseInsensitiveSearch|NSAnchoredSearch].length > 0); } - (BOOL)isJSON { - NSString* contentType = [self contentType]; - return (contentType && - [contentType rangeOfString:@"application/json" - options:NSCaseInsensitiveSearch|NSAnchoredSearch].length > 0); + NSString* contentType = [self contentType]; + return (contentType && + [contentType rangeOfString:@"application/json" + options:NSCaseInsensitiveSearch|NSAnchoredSearch].length > 0); } @end diff --git a/Code/Network/RKURL.m b/Code/Network/RKURL.m index 13fc59c1..bcced9c1 100644 --- a/Code/Network/RKURL.m +++ b/Code/Network/RKURL.m @@ -94,12 +94,12 @@ } - (void)dealloc { - [baseURL release]; - baseURL = nil; - [resourcePath release]; - resourcePath = nil; + [baseURL release]; + baseURL = nil; + [resourcePath release]; + resourcePath = nil; - [super dealloc]; + [super dealloc]; } - (NSDictionary *)queryParameters { diff --git a/Code/ObjectMapping/RKObjectLoader.h b/Code/ObjectMapping/RKObjectLoader.h index 842159e8..bd53de44 100644 --- a/Code/ObjectMapping/RKObjectLoader.h +++ b/Code/ObjectMapping/RKObjectLoader.h @@ -143,7 +143,7 @@ typedef void(^RKObjectLoaderDidLoadObjectsDictionaryBlock)(NSDictionary *diction RKObjectMapping* _serializationMapping; NSString* _serializationMIMEType; NSObject* _sourceObject; - NSObject* _targetObject; + NSObject* _targetObject; dispatch_queue_t _mappingQueue; } diff --git a/Code/ObjectMapping/RKObjectLoader.m b/Code/ObjectMapping/RKObjectLoader.m index 88fe3433..99f2d772 100644 --- a/Code/ObjectMapping/RKObjectLoader.m +++ b/Code/ObjectMapping/RKObjectLoader.m @@ -79,12 +79,12 @@ _mappingProvider = nil; [_sourceObject release]; _sourceObject = nil; - [_targetObject release]; - _targetObject = nil; - [_response release]; - _response = nil; - [_objectMapping release]; - _objectMapping = nil; + [_targetObject release]; + _targetObject = nil; + [_response release]; + _response = nil; + [_objectMapping release]; + _objectMapping = nil; [_result release]; _result = nil; [_serializationMIMEType release]; @@ -100,7 +100,7 @@ [_onDidLoadObjectsDictionary release]; _onDidLoadObjectsDictionary = nil; - [super dealloc]; + [super dealloc]; } - (void)reset { @@ -124,7 +124,7 @@ // 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 { - self.loading = NO; + self.loading = NO; self.loaded = successful; if ([self.delegate respondsToSelector:@selector(objectLoaderDidFinishLoading:)]) { @@ -139,7 +139,7 @@ - (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:)]) { @@ -168,7 +168,7 @@ self.onDidLoadObject([result asObject]); } - [self finalizeLoad:YES]; + [self finalizeLoad:YES]; } #pragma mark - Subclass Hooks @@ -193,7 +193,7 @@ // with the appropriate MIME Type with no content (such as for a successful PUT or DELETE). Make sure we don't generate an error // in these cases id bodyAsString = [self.response bodyAsString]; - RKLogTrace(@"bodyAsString: %@", bodyAsString); + RKLogTrace(@"bodyAsString: %@", bodyAsString); if (bodyAsString == nil || [[bodyAsString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length] == 0) { RKLogDebug(@"Mapping attempted on empty response body..."); if (self.targetObject) { @@ -296,11 +296,11 @@ [[NSNotificationCenter defaultCenter] postNotificationName:RKServiceDidBecomeUnavailableNotification object:self]; } - if ([self.response isFailure]) { + if ([self.response isFailure]) { [self informDelegateOfError:self.response.failureError]; [self didFailLoadWithError:self.response.failureError]; - return NO; + return NO; } else if ([self.response isNoContent]) { // The No Content (204) response will never have a message body or a MIME Type. id resultDictionary = nil; @@ -313,7 +313,7 @@ } [self informDelegateOfObjectLoadWithResultDictionary:resultDictionary]; return NO; - } else if (NO == [self canParseMIMEType:[self.response MIMEType]]) { + } 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]; @@ -331,10 +331,10 @@ } else if ([self.response isError]) { // This is an error and we can map the MIME Type of the response [self handleResponseError]; - return NO; + return NO; } - return YES; + return YES; } - (void)handleResponseError { @@ -390,11 +390,11 @@ NSParameterAssert(error); NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; - if (_cachePolicy & RKRequestCachePolicyLoadOnError && - [self.cache hasResponseForRequest:self]) { + if (_cachePolicy & RKRequestCachePolicyLoadOnError && + [self.cache hasResponseForRequest:self]) { - [self didFinishLoad:[self.cache responseForRequest:self]]; - } else { + [self didFinishLoad:[self.cache responseForRequest:self]]; + } else { if ([_delegate respondsToSelector:@selector(request:didFailLoadWithError:)]) { [_delegate request:self didFailLoadWithError:error]; } @@ -421,19 +421,19 @@ // NOTE: We do NOT call super here. We are overloading the default behavior from RKRequest - (void)didFinishLoad:(RKResponse*)response { NSAssert([NSThread isMainThread], @"RKObjectLoaderDelegate callbacks must occur on the main thread"); - _response = [response retain]; + _response = [response retain]; - if ((_cachePolicy & RKRequestCachePolicyEtag) && [response isNotModified]) { - [_response release]; - _response = nil; - _response = [[self.cache responseForRequest:self] retain]; + if ((_cachePolicy & RKRequestCachePolicyEtag) && [response isNotModified]) { + [_response release]; + _response = nil; + _response = [[self.cache responseForRequest:self] retain]; NSAssert(_response, @"Unexpectedly loaded nil response from cache"); [self updateInternalCacheDate]; - } + } - if (![_response wasLoadedFromCache] && [_response isSuccessful] && (_cachePolicy != RKRequestCachePolicyNone)) { - [self.cache storeResponse:_response forRequest:self]; - } + if (![_response wasLoadedFromCache] && [_response isSuccessful] && (_cachePolicy != RKRequestCachePolicyNone)) { + [self.cache storeResponse:_response forRequest:self]; + } if ([_delegate respondsToSelector:@selector(request:didLoadResponse:)]) { [_delegate request:self didLoadResponse:_response]; @@ -450,7 +450,7 @@ object:self userInfo:userInfo]; - if ([self isResponseMappable]) { + if ([self isResponseMappable]) { // Determine if we are synchronous here or not. if (_sentSynchronously) { NSError* error = nil; @@ -463,7 +463,7 @@ } else { [self performMappingInDispatchQueue]; } - } + } } - (void)setMappingQueue:(dispatch_queue_t)newMappingQueue { @@ -497,12 +497,12 @@ } - (id)initWithResourcePath:(NSString*)resourcePath objectManager:(RKObjectManager*)objectManager delegate:(id)theDelegate { - if ((self = [self initWithURL:[objectManager.baseURL URLByAppendingResourcePath:resourcePath] mappingProvider:objectManager.mappingProvider])) { + if ((self = [self initWithURL:[objectManager.baseURL URLByAppendingResourcePath:resourcePath] mappingProvider:objectManager.mappingProvider])) { [objectManager.client configureRequest:self]; _delegate = theDelegate; - } + } - return self; + return self; } @end diff --git a/Code/ObjectMapping/RKObjectManager.h b/Code/ObjectMapping/RKObjectManager.h index 9f15e901..fc6f3adc 100644 --- a/Code/ObjectMapping/RKObjectManager.h +++ b/Code/ObjectMapping/RKObjectManager.h @@ -40,9 +40,9 @@ extern NSString* const RKObjectManagerDidBecomeOfflineNotification; extern NSString* const RKObjectManagerDidBecomeOnlineNotification; typedef enum { - RKObjectManagerNetworkStatusUnknown, - RKObjectManagerNetworkStatusOffline, - RKObjectManagerNetworkStatusOnline + RKObjectManagerNetworkStatusUnknown, + RKObjectManagerNetworkStatusOffline, + RKObjectManagerNetworkStatusOnline } RKObjectManagerNetworkStatus; @class RKManagedObjectStore; diff --git a/Code/ObjectMapping/RKObjectManager.m b/Code/ObjectMapping/RKObjectManager.m index 96dc3be0..c3bb6fc7 100644 --- a/Code/ObjectMapping/RKObjectManager.m +++ b/Code/ObjectMapping/RKObjectManager.m @@ -108,17 +108,17 @@ static dispatch_queue_t defaultMappingQueue = nil; self.acceptMIMEType = RKMIMETypeJSON; } - return self; + return self; } + (RKObjectManager *)sharedManager { - return sharedManager; + return sharedManager; } + (void)setSharedManager:(RKObjectManager *)manager { - [manager retain]; - [sharedManager release]; - sharedManager = manager; + [manager retain]; + [sharedManager release]; + sharedManager = manager; } + (RKObjectManager *)managerWithBaseURLString:(NSString *)baseURLString { @@ -148,11 +148,11 @@ static dispatch_queue_t defaultMappingQueue = nil; } - (BOOL)isOnline { - return (_networkStatus == RKObjectManagerNetworkStatusOnline); + return (_networkStatus == RKObjectManagerNetworkStatusOnline); } - (BOOL)isOffline { - return (_networkStatus == RKObjectManagerNetworkStatusOffline); + return (_networkStatus == RKObjectManagerNetworkStatusOffline); } - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context @@ -190,15 +190,15 @@ static dispatch_queue_t defaultMappingQueue = nil; } - (void)reachabilityChanged:(NSNotification *)notification { - BOOL isHostReachable = [self.client.reachabilityObserver isNetworkReachable]; + BOOL isHostReachable = [self.client.reachabilityObserver isNetworkReachable]; - _networkStatus = isHostReachable ? RKObjectManagerNetworkStatusOnline : RKObjectManagerNetworkStatusOffline; + _networkStatus = isHostReachable ? RKObjectManagerNetworkStatusOnline : RKObjectManagerNetworkStatusOffline; - if (isHostReachable) { - [[NSNotificationCenter defaultCenter] postNotificationName:RKObjectManagerDidBecomeOnlineNotification object:self]; - } else { - [[NSNotificationCenter defaultCenter] postNotificationName:RKObjectManagerDidBecomeOfflineNotification object:self]; - } + if (isHostReachable) { + [[NSNotificationCenter defaultCenter] postNotificationName:RKObjectManagerDidBecomeOnlineNotification object:self]; + } else { + [[NSNotificationCenter defaultCenter] postNotificationName:RKObjectManagerDidBecomeOfflineNotification object:self]; + } } - (void)setAcceptMIMEType:(NSString *)MIMEType { @@ -264,42 +264,42 @@ static dispatch_queue_t defaultMappingQueue = nil; loader.targetObject = nil; } - return loader; + return loader; } - (void)loadObjectsAtResourcePath:(NSString *)resourcePath delegate:(id)delegate { - RKObjectLoader *loader = [self loaderWithResourcePath:resourcePath]; + RKObjectLoader *loader = [self loaderWithResourcePath:resourcePath]; loader.delegate = delegate; - loader.method = RKRequestMethodGET; + loader.method = RKRequestMethodGET; - [loader send]; + [loader send]; } ///////////////////////////////////////////////////////////// #pragma mark - Object Instance Loaders - (void)getObject:(id)object delegate:(id)delegate { - RKObjectLoader *loader = [self loaderForObject:object method:RKRequestMethodGET]; + RKObjectLoader *loader = [self loaderForObject:object method:RKRequestMethodGET]; loader.delegate = delegate; - [loader send]; + [loader send]; } - (void)postObject:(id)object delegate:(id)delegate { - RKObjectLoader *loader = [self loaderForObject:object method:RKRequestMethodPOST]; + RKObjectLoader *loader = [self loaderForObject:object method:RKRequestMethodPOST]; loader.delegate = delegate; - [loader send]; + [loader send]; } - (void)putObject:(id)object delegate:(id)delegate { - RKObjectLoader *loader = [self loaderForObject:object method:RKRequestMethodPUT]; + RKObjectLoader *loader = [self loaderForObject:object method:RKRequestMethodPUT]; loader.delegate = delegate; - [loader send]; + [loader send]; } - (void)deleteObject:(id)object delegate:(id)delegate { - RKObjectLoader *loader = [self loaderForObject:object method:RKRequestMethodDELETE]; + RKObjectLoader *loader = [self loaderForObject:object method:RKRequestMethodDELETE]; loader.delegate = delegate; - [loader send]; + [loader send]; } #if NS_BLOCKS_AVAILABLE @@ -307,13 +307,13 @@ static dispatch_queue_t defaultMappingQueue = nil; #pragma mark - Block Configured Object Loaders - (void)loadObjectsAtResourcePath:(NSString*)resourcePath usingBlock:(void(^)(RKObjectLoader *))block { - RKObjectLoader* loader = [self loaderWithResourcePath:resourcePath]; - loader.method = RKRequestMethodGET; + RKObjectLoader* loader = [self loaderWithResourcePath:resourcePath]; + loader.method = RKRequestMethodGET; // Yield to the block for setup block(loader); - [loader send]; + [loader send]; } - (void)sendObject:(id)object toResourcePath:(NSString *)resourcePath usingBlock:(void(^)(RKObjectLoader *))block { @@ -361,21 +361,21 @@ static dispatch_queue_t defaultMappingQueue = nil; } - (void)postObject:(id)object mapResponseWith:(RKObjectMapping *)objectMapping delegate:(id)delegate { - [self sendObject:object method:RKRequestMethodPOST usingBlock:^(RKObjectLoader *loader) { + [self sendObject:object method:RKRequestMethodPOST usingBlock:^(RKObjectLoader *loader) { loader.delegate = delegate; loader.objectMapping = objectMapping; }]; } - (void)putObject:(id)object mapResponseWith:(RKObjectMapping *)objectMapping delegate:(id)delegate { - [self sendObject:object method:RKRequestMethodPUT usingBlock:^(RKObjectLoader *loader) { + [self sendObject:object method:RKRequestMethodPUT usingBlock:^(RKObjectLoader *loader) { loader.delegate = delegate; loader.objectMapping = objectMapping; }]; } - (void)deleteObject:(id)object mapResponseWith:(RKObjectMapping *)objectMapping delegate:(id)delegate { - [self sendObject:object method:RKRequestMethodDELETE usingBlock:^(RKObjectLoader *loader) { + [self sendObject:object method:RKRequestMethodDELETE usingBlock:^(RKObjectLoader *loader) { loader.delegate = delegate; loader.objectMapping = objectMapping; }]; @@ -419,7 +419,7 @@ static dispatch_queue_t defaultMappingQueue = nil; } + (RKObjectManager *)objectManagerWithBaseURL:(NSURL *)baseURL { - return [self managerWithBaseURL:baseURL]; + return [self managerWithBaseURL:baseURL]; } - (RKObjectLoader *)objectLoaderWithResourcePath:(NSString *)resourcePath delegate:(id)delegate { @@ -436,12 +436,12 @@ static dispatch_queue_t defaultMappingQueue = nil; } - (void)loadObjectsAtResourcePath:(NSString *)resourcePath objectMapping:(RKObjectMapping *)objectMapping delegate:(id)delegate { - RKObjectLoader *loader = [self loaderWithResourcePath:resourcePath]; + RKObjectLoader *loader = [self loaderWithResourcePath:resourcePath]; loader.delegate = delegate; - loader.method = RKRequestMethodGET; + loader.method = RKRequestMethodGET; loader.objectMapping = objectMapping; - [loader send]; + [loader send]; } @end diff --git a/Code/ObjectMapping/RKObjectMapping.m b/Code/ObjectMapping/RKObjectMapping.m index a515f4ba..373151f5 100644 --- a/Code/ObjectMapping/RKObjectMapping.m +++ b/Code/ObjectMapping/RKObjectMapping.m @@ -106,8 +106,8 @@ NSString* const RKObjectMappingNestingAttributeKeyName = @" { - NSMutableDictionary* _routes; + NSMutableDictionary* _routes; } /** diff --git a/Code/ObjectMapping/RKParserRegistry.h b/Code/ObjectMapping/RKParserRegistry.h index b7cbc124..0e0d4c3f 100644 --- a/Code/ObjectMapping/RKParserRegistry.h +++ b/Code/ObjectMapping/RKParserRegistry.h @@ -29,7 +29,7 @@ */ @interface RKParserRegistry : NSObject { NSMutableDictionary *_MIMETypeToParserClasses; - NSMutableArray *_MIMETypeToParserClassesRegularExpressions; + NSMutableArray *_MIMETypeToParserClassesRegularExpressions; } /** diff --git a/Code/ObjectMapping/RKParserRegistry.m b/Code/ObjectMapping/RKParserRegistry.m index 70d8ecf3..16ede88d 100644 --- a/Code/ObjectMapping/RKParserRegistry.m +++ b/Code/ObjectMapping/RKParserRegistry.m @@ -51,26 +51,26 @@ RKParserRegistry *gSharedRegistry; - (void)dealloc { [_MIMETypeToParserClasses release]; - [_MIMETypeToParserClassesRegularExpressions release]; + [_MIMETypeToParserClassesRegularExpressions release]; [super dealloc]; } - (Class)parserClassForMIMEType:(NSString *)MIMEType { - id parserClass = [_MIMETypeToParserClasses objectForKey:MIMEType]; + id parserClass = [_MIMETypeToParserClasses objectForKey:MIMEType]; #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 1070 || __IPHONE_OS_VERSION_MAX_ALLOWED >= 40000 - if (!parserClass) - { - for (NSArray *regexAndClass in _MIMETypeToParserClassesRegularExpressions) { - NSRegularExpression *regex = [regexAndClass objectAtIndex:0]; - NSUInteger numberOfMatches = [regex numberOfMatchesInString:MIMEType options:0 range:NSMakeRange(0, [MIMEType length])]; - if (numberOfMatches) { - parserClass = [regexAndClass objectAtIndex:1]; - break; - } - } - } + if (!parserClass) + { + for (NSArray *regexAndClass in _MIMETypeToParserClassesRegularExpressions) { + NSRegularExpression *regex = [regexAndClass objectAtIndex:0]; + NSUInteger numberOfMatches = [regex numberOfMatchesInString:MIMEType options:0 range:NSMakeRange(0, [MIMEType length])]; + if (numberOfMatches) { + parserClass = [regexAndClass objectAtIndex:1]; + break; + } + } + } #endif - return parserClass; + return parserClass; } - (void)setParserClass:(Class)parserClass forMIMEType:(NSString *)MIMEType { @@ -80,7 +80,7 @@ RKParserRegistry *gSharedRegistry; #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 1070 || __IPHONE_OS_VERSION_MAX_ALLOWED >= 40000 - (void)setParserClass:(Class)parserClass forMIMETypeRegularExpression:(NSRegularExpression *)MIMETypeRegex { - NSArray *expressionAndClass = [NSArray arrayWithObjects:MIMETypeRegex, parserClass, nil]; + NSArray *expressionAndClass = [NSArray arrayWithObjects:MIMETypeRegex, parserClass, nil]; [_MIMETypeToParserClassesRegularExpressions addObject:expressionAndClass]; } diff --git a/Code/Support/NSArray+RKAdditions.m b/Code/Support/NSArray+RKAdditions.m index bb58701d..f632b1bb 100644 --- a/Code/Support/NSArray+RKAdditions.m +++ b/Code/Support/NSArray+RKAdditions.m @@ -15,43 +15,43 @@ // Code adapted from: https://gist.github.com/1243312 NSMutableArray *sections = [NSMutableArray array]; - // If we don't contain any items, return an empty collection of sections. - if([self count] == 0) { - return sections; + // If we don't contain any items, return an empty collection of sections. + if([self count] == 0) { + return sections; } - // Create the first section and establish the first section's grouping value. - NSMutableArray *sectionItems = [NSMutableArray array]; - id currentGroup = [[self objectAtIndex:0] valueForKeyPath:keyPath]; + // Create the first section and establish the first section's grouping value. + NSMutableArray *sectionItems = [NSMutableArray array]; + id currentGroup = [[self objectAtIndex:0] valueForKeyPath:keyPath]; - // Iterate over our items, placing them in the appropriate section and - // creating new sections when necessary. - for (id item in self) { - // Retrieve the grouping value from the current item. - id itemGroup = [item valueForKeyPath:keyPath]; + // Iterate over our items, placing them in the appropriate section and + // creating new sections when necessary. + for (id item in self) { + // Retrieve the grouping value from the current item. + id itemGroup = [item valueForKeyPath:keyPath]; - // Compare the current item's grouping value to the current section's - // grouping value. - if (![itemGroup isEqual:currentGroup] && (currentGroup != nil || itemGroup != nil)) { - // The current item doesn't belong in the current section, so - // store the section we've been building and create a new one, - // caching the new grouping value. - [sections addObject:sectionItems]; - sectionItems = [NSMutableArray array]; - currentGroup = itemGroup; - } + // Compare the current item's grouping value to the current section's + // grouping value. + if (![itemGroup isEqual:currentGroup] && (currentGroup != nil || itemGroup != nil)) { + // The current item doesn't belong in the current section, so + // store the section we've been building and create a new one, + // caching the new grouping value. + [sections addObject:sectionItems]; + sectionItems = [NSMutableArray array]; + currentGroup = itemGroup; + } - // Add the item to the appropriate section. - [sectionItems addObject:item]; - } - - // If we were adding items to a section that has not yet been added - // to the aggregate section collection, add it now. - if ([sectionItems count] > 0) { - [sections addObject:sectionItems]; + // Add the item to the appropriate section. + [sectionItems addObject:item]; } - return sections; + // If we were adding items to a section that has not yet been added + // to the aggregate section collection, add it now. + if ([sectionItems count] > 0) { + [sections addObject:sectionItems]; + } + + return sections; } @end diff --git a/Code/Support/NSBundle+RKAdditions.m b/Code/Support/NSBundle+RKAdditions.m index 0579bde2..eed3412e 100644 --- a/Code/Support/NSBundle+RKAdditions.m +++ b/Code/Support/NSBundle+RKAdditions.m @@ -68,12 +68,12 @@ 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 "); } - return fixtureData; + return fixtureData; } #if TARGET_OS_IPHONE diff --git a/Code/Support/NSDictionary+RKAdditions.m b/Code/Support/NSDictionary+RKAdditions.m index 0aac48af..dc5d7945 100644 --- a/Code/Support/NSDictionary+RKAdditions.m +++ b/Code/Support/NSDictionary+RKAdditions.m @@ -27,14 +27,14 @@ RK_FIX_CATEGORY_BUG(NSDictionary_RKAdditions) @implementation NSDictionary (RKAdditions) + (id)dictionaryWithKeysAndObjects:(id)firstKey, ... { - va_list args; + 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); + id value = va_arg(args, id); [keys addObject:key]; - [values addObject:value]; + [values addObject:value]; } va_end(args); @@ -92,7 +92,7 @@ RK_FIX_CATEGORY_BUG(NSDictionary_RKAdditions) NSString *path = inPath ? [inPath stringByAppendingFormat:@"[%@]", encodedKey] : encodedKey; if ([value isKindOfClass:[NSArray class]]) { - for (id item in value) { + for (id item in value) { if ([item isKindOfClass:[NSDictionary class]] || [item isKindOfClass:[NSMutableDictionary class]]) { [item URLEncodeParts:parts path:[path stringByAppendingString:@"[]"]]; } else { diff --git a/Code/Support/NSString+RKAdditions.m b/Code/Support/NSString+RKAdditions.m index 20ba3aa8..b53e85d8 100644 --- a/Code/Support/NSString+RKAdditions.m +++ b/Code/Support/NSString+RKAdditions.m @@ -126,7 +126,7 @@ RK_FIX_CATEGORY_BUG(NSString_RKAdditions) NULL, legalURLCharactersToBeEscaped, kCFStringEncodingUTF8); - if (encodedString) { + if (encodedString) { return [(NSString *)encodedString autorelease]; } diff --git a/Code/Support/Parsers/JSON/RKJSONParserJSONKit.m b/Code/Support/Parsers/JSON/RKJSONParserJSONKit.m index 5a29e3b5..56f6ebf7 100644 --- a/Code/Support/Parsers/JSON/RKJSONParserJSONKit.m +++ b/Code/Support/Parsers/JSON/RKJSONParserJSONKit.m @@ -32,12 +32,12 @@ @implementation RKJSONParserJSONKit - (NSDictionary*)objectFromString:(NSString*)string error:(NSError**)error { - RKLogTrace(@"string='%@'", string); + RKLogTrace(@"string='%@'", string); return [string objectFromJSONStringWithParseOptions:JKParseOptionStrict error:error]; } - (NSString*)stringFromObject:(id)object error:(NSError**)error { - return [object JSONStringWithOptions:JKSerializeOptionNone error:error]; + return [object JSONStringWithOptions:JKSerializeOptionNone error:error]; } @end diff --git a/Code/Support/RKCache.h b/Code/Support/RKCache.h index 95e8d59a..1b5d590f 100644 --- a/Code/Support/RKCache.h +++ b/Code/Support/RKCache.h @@ -19,8 +19,8 @@ // @interface RKCache : NSObject { - NSString* _cachePath; - NSRecursiveLock* _cacheLock; + NSString* _cachePath; + NSRecursiveLock* _cacheLock; } @property (nonatomic, readonly) NSString* cachePath; diff --git a/Code/Support/RKCache.m b/Code/Support/RKCache.m index 7b451404..cc10686e 100644 --- a/Code/Support/RKCache.m +++ b/Code/Support/RKCache.m @@ -29,46 +29,46 @@ - (id)initWithPath:(NSString*)cachePath subDirectories:(NSArray*)subDirectories { self = [super init]; - if (self) { - _cachePath = [cachePath copy]; - _cacheLock = [[NSRecursiveLock alloc] init]; + if (self) { + _cachePath = [cachePath copy]; + _cacheLock = [[NSRecursiveLock alloc] init]; - NSFileManager* fileManager = [NSFileManager defaultManager]; - NSMutableArray* pathArray = [NSMutableArray arrayWithObject:_cachePath]; + NSFileManager* fileManager = [NSFileManager defaultManager]; + NSMutableArray* pathArray = [NSMutableArray arrayWithObject:_cachePath]; for (NSString* subDirectory in subDirectories) { [pathArray addObject:[_cachePath stringByAppendingPathComponent:subDirectory]]; } - for (NSString* path in pathArray) { - BOOL isDirectory = NO; - BOOL fileExists = [fileManager fileExistsAtPath:path isDirectory:&isDirectory]; - if (!fileExists) { - NSError* error = nil; - BOOL created = [fileManager createDirectoryAtPath:path - withIntermediateDirectories:YES - attributes:nil - error:&error]; - if (!created || error != nil) { - RKLogError(@"Failed to create cache directory at %@: error %@", path, [error localizedDescription]); - } else { + for (NSString* path in pathArray) { + BOOL isDirectory = NO; + BOOL fileExists = [fileManager fileExistsAtPath:path isDirectory:&isDirectory]; + if (!fileExists) { + NSError* error = nil; + BOOL created = [fileManager createDirectoryAtPath:path + withIntermediateDirectories:YES + attributes:nil + error:&error]; + if (!created || error != nil) { + RKLogError(@"Failed to create cache directory at %@: error %@", path, [error localizedDescription]); + } else { RKLogDebug(@"Created cache storage at path '%@'", path); } - } else { + } else { if (!isDirectory) { RKLogWarning(@"Skipped creation of cache directory as non-directory file exists at path: %@", path); } - } - } - } - return self; + } + } + } + return self; } - (void)dealloc { - [_cachePath release]; - _cachePath = nil; - [_cacheLock release]; - _cacheLock = nil; - [super dealloc]; + [_cachePath release]; + _cachePath = nil; + [_cacheLock release]; + _cacheLock = nil; + [super dealloc]; } - (NSString*)cachePath { @@ -76,22 +76,22 @@ } - (NSString*)pathForCacheKey:(NSString*)cacheKey { - [_cacheLock lock]; - NSString* pathForCacheKey = [_cachePath stringByAppendingPathComponent:cacheKey]; - [_cacheLock unlock]; + [_cacheLock lock]; + NSString* pathForCacheKey = [_cachePath stringByAppendingPathComponent:cacheKey]; + [_cacheLock unlock]; RKLogTrace(@"Found cachePath '%@' for %@", pathForCacheKey, cacheKey); - return pathForCacheKey; + return pathForCacheKey; } - (BOOL)hasEntry:(NSString*)cacheKey { [_cacheLock lock]; - BOOL hasEntry = NO; - NSFileManager* fileManager = [NSFileManager defaultManager]; - NSString* cachePath = [self pathForCacheKey:cacheKey]; - hasEntry = [fileManager fileExistsAtPath:cachePath]; - [_cacheLock unlock]; + BOOL hasEntry = NO; + NSFileManager* fileManager = [NSFileManager defaultManager]; + NSString* cachePath = [self pathForCacheKey:cacheKey]; + hasEntry = [fileManager fileExistsAtPath:cachePath]; + [_cacheLock unlock]; RKLogTrace(@"Determined hasEntry: %@ => %@", cacheKey, hasEntry ? @"YES" : @"NO"); - return hasEntry; + return hasEntry; } - (void)writeDictionary:(NSDictionary*)dictionary withCacheKey:(NSString*)cacheKey { @@ -147,87 +147,87 @@ [_cacheLock lock]; NSData* data = nil; NSString* cachePath = [self pathForCacheKey:cacheKey]; - if (cachePath) { - data = [NSData dataWithContentsOfFile:cachePath]; + if (cachePath) { + data = [NSData dataWithContentsOfFile:cachePath]; if (data) { RKLogDebug(@"Read cached data '%@' from cachePath '%@' for '%@'", data, cachePath, cacheKey); } else { RKLogDebug(@"Read nil cached data from cachePath '%@' for '%@'", cachePath, cacheKey); } - } - [_cacheLock unlock]; - return data; + } + [_cacheLock unlock]; + return data; } - (void)invalidateEntry:(NSString*)cacheKey { [_cacheLock lock]; RKLogDebug(@"Invalidating cache entry for '%@'", cacheKey); NSString* cachePath = [self pathForCacheKey:cacheKey]; - if (cachePath) { - NSFileManager* fileManager = [NSFileManager defaultManager]; - [fileManager removeItemAtPath:cachePath error:NULL]; + if (cachePath) { + NSFileManager* fileManager = [NSFileManager defaultManager]; + [fileManager removeItemAtPath:cachePath error:NULL]; RKLogTrace(@"Removed cache entry at path '%@' for '%@'", cachePath, cacheKey); - } - [_cacheLock unlock]; + } + [_cacheLock unlock]; } - (void)invalidateSubDirectory:(NSString*)subDirectory { [_cacheLock lock]; - if (_cachePath && subDirectory) { + if (_cachePath && 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]; + BOOL isDirectory = NO; + BOOL fileExists = [fileManager fileExistsAtPath:subDirectoryPath isDirectory:&isDirectory]; - if (fileExists && isDirectory) { - NSError* error = nil; - NSArray* cacheEntries = [fileManager contentsOfDirectoryAtPath:subDirectoryPath error:&error]; + if (fileExists && isDirectory) { + NSError* error = nil; + NSArray* cacheEntries = [fileManager contentsOfDirectoryAtPath:subDirectoryPath error:&error]; - if (nil == error) { - 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); - } - } - } else { - RKLogWarning(@"Failed to fetch list of cache entries for cache path: %@", subDirectoryPath); - } - } - } - [_cacheLock unlock]; + if (nil == error) { + 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); + } + } + } else { + RKLogWarning(@"Failed to fetch list of cache entries for cache path: %@", subDirectoryPath); + } + } + } + [_cacheLock unlock]; } - (void)invalidateAll { [_cacheLock lock]; - if (_cachePath) { + 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]; + BOOL isDirectory = NO; + BOOL fileExists = [fileManager fileExistsAtPath:_cachePath isDirectory:&isDirectory]; - if (fileExists && isDirectory) { - NSError* error = nil; - NSArray* cacheEntries = [fileManager contentsOfDirectoryAtPath:_cachePath error:&error]; + if (fileExists && isDirectory) { + NSError* error = nil; + NSArray* cacheEntries = [fileManager contentsOfDirectoryAtPath:_cachePath error:&error]; - if (nil == error) { - 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); - } - } - } else { - RKLogWarning(@"Failed to fetch list of cache entries for cache path: %@", _cachePath); - } - } - } - [_cacheLock unlock]; + if (nil == error) { + 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); + } + } + } else { + RKLogWarning(@"Failed to fetch list of cache entries for cache path: %@", _cachePath); + } + } + } + [_cacheLock unlock]; } @end diff --git a/Code/Support/RKDotNetDateFormatter.m b/Code/Support/RKDotNetDateFormatter.m index 423c1f1f..20685ef0 100644 --- a/Code/Support/RKDotNetDateFormatter.m +++ b/Code/Support/RKDotNetDateFormatter.m @@ -66,10 +66,10 @@ NSTimeInterval millisecondsFromSeconds(NSTimeInterval seconds); } - (BOOL)getObjectValue:(id *)outValue forString:(NSString *)string errorDescription:(NSString **)error { - NSDate *date = [self dateFromString:string]; - if (outValue) - *outValue = date; - return (date != nil); + NSDate *date = [self dateFromString:string]; + if (outValue) + *outValue = date; + return (date != nil); } - (id)init { diff --git a/Code/Support/RKMutableBlockDictionary.m b/Code/Support/RKMutableBlockDictionary.m index 4d61f7d9..a2dbbf58 100644 --- a/Code/Support/RKMutableBlockDictionary.m +++ b/Code/Support/RKMutableBlockDictionary.m @@ -64,7 +64,7 @@ typedef id (^RKMutableBlockDictionaryValueBlock)(); @implementation RKMutableBlockDictionary - (id)init { - return [self initWithCapacity:0]; + return [self initWithCapacity:0]; } - (id)initWithCapacity:(NSUInteger)capacity { @@ -82,7 +82,7 @@ typedef id (^RKMutableBlockDictionaryValueBlock)(); } - (id)copy { - return [self mutableCopy]; + return [self mutableCopy]; } - (void)setObject:(id)anObject forKey:(id)aKey { diff --git a/Code/Support/RKOrderedDictionary.h b/Code/Support/RKOrderedDictionary.h index fe03c2d5..bbbc68e1 100644 --- a/Code/Support/RKOrderedDictionary.h +++ b/Code/Support/RKOrderedDictionary.h @@ -31,8 +31,8 @@ // Borrowed from Matt Gallagher - http://cocoawithlove.com/2008/12/ordereddictionary-subclassing-cocoa.html @interface RKOrderedDictionary : NSMutableDictionary { - NSMutableDictionary *dictionary; - NSMutableArray *array; + NSMutableDictionary *dictionary; + NSMutableArray *array; } /** diff --git a/Code/Support/RKOrderedDictionary.m b/Code/Support/RKOrderedDictionary.m index 3ff6e8e2..2087c598 100644 --- a/Code/Support/RKOrderedDictionary.m +++ b/Code/Support/RKOrderedDictionary.m @@ -26,126 +26,126 @@ NSString *RKDescriptionForObject(NSObject *object, id locale, NSUInteger indent); NSString *RKDescriptionForObject(NSObject *object, id locale, NSUInteger indent) { - NSString *objectString; - if ([object isKindOfClass:[NSString class]]) - { - objectString = (NSString *)[[object retain] autorelease]; - } - else if ([object respondsToSelector:@selector(descriptionWithLocale:indent:)]) - { - objectString = [(NSDictionary *)object descriptionWithLocale:locale indent:indent]; - } - else if ([object respondsToSelector:@selector(descriptionWithLocale:)]) - { - objectString = [(NSSet *)object descriptionWithLocale:locale]; - } - else - { - objectString = [object description]; - } - return objectString; + NSString *objectString; + if ([object isKindOfClass:[NSString class]]) + { + objectString = (NSString *)[[object retain] autorelease]; + } + else if ([object respondsToSelector:@selector(descriptionWithLocale:indent:)]) + { + objectString = [(NSDictionary *)object descriptionWithLocale:locale indent:indent]; + } + else if ([object respondsToSelector:@selector(descriptionWithLocale:)]) + { + objectString = [(NSSet *)object descriptionWithLocale:locale]; + } + else + { + objectString = [object description]; + } + return objectString; } @implementation RKOrderedDictionary - (id)init { - return [self initWithCapacity:0]; + return [self initWithCapacity:0]; } - (id)initWithCapacity:(NSUInteger)capacity { - self = [super init]; - if (self != nil) - { - dictionary = [[NSMutableDictionary alloc] initWithCapacity:capacity]; - array = [[NSMutableArray alloc] initWithCapacity:capacity]; - } - return self; + self = [super init]; + if (self != nil) + { + dictionary = [[NSMutableDictionary alloc] initWithCapacity:capacity]; + array = [[NSMutableArray alloc] initWithCapacity:capacity]; + } + return self; } - (void)dealloc { - [dictionary release]; - [array release]; - [super dealloc]; + [dictionary release]; + [array release]; + [super dealloc]; } - (id)copy { - return [self mutableCopy]; + return [self mutableCopy]; } - (void)setObject:(id)anObject forKey:(id)aKey { - if (![dictionary objectForKey:aKey]) - { - [array addObject:aKey]; - } - [dictionary setObject:anObject forKey:aKey]; + if (![dictionary objectForKey:aKey]) + { + [array addObject:aKey]; + } + [dictionary setObject:anObject forKey:aKey]; } - (void)removeObjectForKey:(id)aKey { - [dictionary removeObjectForKey:aKey]; - [array removeObject:aKey]; + [dictionary removeObjectForKey:aKey]; + [array removeObject:aKey]; } - (NSUInteger)count { - return [dictionary count]; + return [dictionary count]; } - (id)objectForKey:(id)aKey { - return [dictionary objectForKey:aKey]; + return [dictionary objectForKey:aKey]; } - (NSEnumerator *)keyEnumerator { - return [array objectEnumerator]; + return [array objectEnumerator]; } - (NSEnumerator *)reverseKeyEnumerator { - return [array reverseObjectEnumerator]; + return [array reverseObjectEnumerator]; } - (void)insertObject:(id)anObject forKey:(id)aKey atIndex:(NSUInteger)anIndex { - if ([dictionary objectForKey:aKey]) - { - [self removeObjectForKey:aKey]; - } - [array insertObject:aKey atIndex:anIndex]; - [dictionary setObject:anObject forKey:aKey]; + if ([dictionary objectForKey:aKey]) + { + [self removeObjectForKey:aKey]; + } + [array insertObject:aKey atIndex:anIndex]; + [dictionary setObject:anObject forKey:aKey]; } - (id)keyAtIndex:(NSUInteger)anIndex { - return [array objectAtIndex:anIndex]; + return [array objectAtIndex:anIndex]; } - (NSString *)descriptionWithLocale:(id)locale indent:(NSUInteger)level { - NSMutableString *indentString = [NSMutableString string]; - NSUInteger i, count = level; - for (i = 0; i < count; i++) - { - [indentString appendFormat:@" "]; - } + NSMutableString *indentString = [NSMutableString string]; + NSUInteger i, count = level; + for (i = 0; i < count; i++) + { + [indentString appendFormat:@" "]; + } - NSMutableString *description = [NSMutableString string]; - [description appendFormat:@"%@{\n", indentString]; - for (NSObject *key in self) - { - [description appendFormat:@"%@ %@ = %@;\n", + NSMutableString *description = [NSMutableString string]; + [description appendFormat:@"%@{\n", indentString]; + for (NSObject *key in self) + { + [description appendFormat:@"%@ %@ = %@;\n", indentString, RKDescriptionForObject(key, locale, level), RKDescriptionForObject([self objectForKey:key], locale, level)]; - } - [description appendFormat:@"%@}\n", indentString]; - return description; + } + [description appendFormat:@"%@}\n", indentString]; + return description; } @end diff --git a/Code/Support/RKPortCheck.m b/Code/Support/RKPortCheck.m index 788dc73f..0d95bc64 100644 --- a/Code/Support/RKPortCheck.m +++ b/Code/Support/RKPortCheck.m @@ -72,13 +72,13 @@ _run = YES; // Create Internet domain socket - if ((sd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { + if ((sd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { _open = NO; return; - } + } - // Try to connect to the port - _open = (connect(sd,(struct sockaddr *) &_remote_saddr, sizeof(_remote_saddr)) == 0); + // Try to connect to the port + _open = (connect(sd,(struct sockaddr *) &_remote_saddr, sizeof(_remote_saddr)) == 0); if (_open) { close(sd); diff --git a/Code/Support/RKSearchEngine.h b/Code/Support/RKSearchEngine.h index 9675111c..918261b3 100644 --- a/Code/Support/RKSearchEngine.h +++ b/Code/Support/RKSearchEngine.h @@ -46,13 +46,13 @@ typedef enum { The search text should be matched inclusively using AND. Matches will include all search terms. */ - RKSearchModeAnd, + RKSearchModeAnd, /** The search text should be matched exclusively using OR. Matches will include any search terms. */ - RKSearchModeOr + RKSearchModeOr } RKSearchMode; /** diff --git a/Code/Support/RKSearchEngine.m b/Code/Support/RKSearchEngine.m index 4c77c6f1..a6bfa708 100644 --- a/Code/Support/RKSearchEngine.m +++ b/Code/Support/RKSearchEngine.m @@ -29,20 +29,20 @@ + (id)searchEngine { - return [[[RKSearchEngine alloc] init] autorelease]; + return [[[RKSearchEngine alloc] init] autorelease]; } - (id)init { self = [super init]; - if (self) { - mode = RKSearchModeOr; - tokenizeQuery = YES; - stripsWhitespace = YES; - caseSensitive = NO; - } + if (self) { + mode = RKSearchModeOr; + tokenizeQuery = YES; + stripsWhitespace = YES; + caseSensitive = NO; + } - return self; + return self; } #pragma mark Private @@ -50,47 +50,47 @@ - (NSString *)stripWhitespaceIfNecessary:(NSString *)string { - if (stripsWhitespace) { - return [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; - } + if (stripsWhitespace) { + return [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; + } return string; } - (NSArray *)tokenizeOrCollect:(NSString *)string { - if (self.tokenizeQuery) { - return [string componentsSeparatedByString:@" "]; - } + if (self.tokenizeQuery) { + return [string componentsSeparatedByString:@" "]; + } return [NSArray arrayWithObject:string]; } - (NSArray *)searchWithTerms:(NSArray*)searchTerms onProperties:(NSArray *)properties inCollection:(NSArray *)collection compoundSelector:(SEL)selector { - NSPredicate *searchPredicate = nil; + NSPredicate *searchPredicate = nil; - // do any of these properties contain all of these terms - NSMutableArray *propertyPredicates = [NSMutableArray array]; - for (NSString *property in properties) { - NSMutableArray *termPredicates = [NSMutableArray array]; - for (NSString *searchTerm in searchTerms) { - NSPredicate *predicate; - if (self.isCaseSensitive) { - predicate = [NSPredicate predicateWithFormat:@"(%K contains %@)", property, searchTerm]; - } else { - predicate = [NSPredicate predicateWithFormat:@"(%K contains[cd] %@)", property, searchTerm]; - } - [termPredicates addObject:predicate]; - } + // do any of these properties contain all of these terms + NSMutableArray *propertyPredicates = [NSMutableArray array]; + for (NSString *property in properties) { + NSMutableArray *termPredicates = [NSMutableArray array]; + for (NSString *searchTerm in searchTerms) { + NSPredicate *predicate; + if (self.isCaseSensitive) { + predicate = [NSPredicate predicateWithFormat:@"(%K contains %@)", property, searchTerm]; + } else { + predicate = [NSPredicate predicateWithFormat:@"(%K contains[cd] %@)", property, searchTerm]; + } + [termPredicates addObject:predicate]; + } - // build a predicate for all of the search terms - NSPredicate *termsPredicate = [NSCompoundPredicate performSelector:selector withObject:termPredicates]; - [propertyPredicates addObject:termsPredicate]; - } + // build a predicate for all of the search terms + NSPredicate *termsPredicate = [NSCompoundPredicate performSelector:selector withObject:termPredicates]; + [propertyPredicates addObject:termsPredicate]; + } - searchPredicate = [NSCompoundPredicate orPredicateWithSubpredicates:propertyPredicates]; - return [collection filteredArrayUsingPredicate:searchPredicate]; + searchPredicate = [NSCompoundPredicate orPredicateWithSubpredicates:propertyPredicates]; + return [collection filteredArrayUsingPredicate:searchPredicate]; } #pragma mark Public @@ -98,23 +98,23 @@ - (NSArray *)searchFor:(NSString *)searchText inCollection:(NSArray *)collection { - NSArray *properties = [NSArray arrayWithObject:@"searchableText"]; - return [self searchFor:searchText onProperties:properties inCollection:collection]; + NSArray *properties = [NSArray arrayWithObject:@"searchableText"]; + return [self searchFor:searchText onProperties:properties inCollection:collection]; } - (NSArray *)searchFor:(NSString *)searchText onProperties:(NSArray *)properties inCollection:(NSArray *)collection { - NSString *searchQuery = [[searchText copy] autorelease]; - searchQuery = [self stripWhitespaceIfNecessary:searchQuery]; - NSArray *searchTerms = [self tokenizeOrCollect:searchQuery]; + NSString *searchQuery = [[searchText copy] autorelease]; + searchQuery = [self stripWhitespaceIfNecessary:searchQuery]; + NSArray *searchTerms = [self tokenizeOrCollect:searchQuery]; - if (mode == RKSearchModeOr) { - return [self searchWithTerms:searchTerms onProperties:properties inCollection:collection compoundSelector:@selector(orPredicateWithSubpredicates:)]; - } else if (mode == RKSearchModeAnd) { - return [self searchWithTerms:searchTerms onProperties:properties inCollection:collection compoundSelector:@selector(andPredicateWithSubpredicates:)]; - } else { - return nil; - } + if (mode == RKSearchModeOr) { + return [self searchWithTerms:searchTerms onProperties:properties inCollection:collection compoundSelector:@selector(orPredicateWithSubpredicates:)]; + } else if (mode == RKSearchModeAnd) { + return [self searchWithTerms:searchTerms onProperties:properties inCollection:collection compoundSelector:@selector(andPredicateWithSubpredicates:)]; + } else { + return nil; + } } @end diff --git a/Code/Testing/RKTestNotificationObserver.m b/Code/Testing/RKTestNotificationObserver.m index da512de5..ba20a39e 100644 --- a/Code/Testing/RKTestNotificationObserver.m +++ b/Code/Testing/RKTestNotificationObserver.m @@ -46,16 +46,16 @@ - (id)init { self = [super init]; - if (self) { + if (self) { timeout = 5; - awaitingNotification = NO; - } - return self; + awaitingNotification = NO; + } + return self; } - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; - [super dealloc]; + [super dealloc]; } - (void)waitForNotification { @@ -66,16 +66,16 @@ name:self.name object:self.object]; - awaitingNotification = YES; - NSDate *startDate = [NSDate date]; + awaitingNotification = YES; + NSDate *startDate = [NSDate date]; - while (self.isAwaitingNotification) { - [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; - if ([[NSDate date] timeIntervalSinceDate:startDate] > self.timeout) { - [NSException raise:nil format:@"*** Operation timed out after %f seconds...", self.timeout]; - awaitingNotification = NO; - } - } + while (self.isAwaitingNotification) { + [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; + if ([[NSDate date] timeIntervalSinceDate:startDate] > self.timeout) { + [NSException raise:nil format:@"*** Operation timed out after %f seconds...", self.timeout]; + awaitingNotification = NO; + } + } } - (void)processNotification:(NSNotification*)notification { diff --git a/Code/Testing/RKTestResponseLoader.m b/Code/Testing/RKTestResponseLoader.m index 9362b71b..a3e47cda 100644 --- a/Code/Testing/RKTestResponseLoader.m +++ b/Code/Testing/RKTestResponseLoader.m @@ -53,42 +53,42 @@ NSString * const RKTestResponseLoaderTimeoutException = @"RKTestResponseLoaderTi - (id)init { self = [super init]; - if (self) { - timeout = 4; - awaitingResponse = NO; - } + if (self) { + timeout = 4; + awaitingResponse = NO; + } - return self; + return self; } - (void)dealloc { - [response release]; + [response release]; response = nil; - [error release]; + [error release]; error = nil; [objects release]; objects = nil; - [super dealloc]; + [super dealloc]; } - (void)waitForResponse { - awaitingResponse = YES; - NSDate *startDate = [NSDate date]; + awaitingResponse = YES; + NSDate *startDate = [NSDate date]; RKLogTrace(@"%@ Awaiting response loaded from for %f seconds...", self, self.timeout); - while (awaitingResponse) { - [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; - if ([[NSDate date] timeIntervalSinceDate:startDate] > self.timeout) { - [NSException raise:RKTestResponseLoaderTimeoutException format:@"*** Operation timed out after %f seconds...", self.timeout]; - awaitingResponse = NO; - } - } + while (awaitingResponse) { + [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; + if ([[NSDate date] timeIntervalSinceDate:startDate] > self.timeout) { + [NSException raise:RKTestResponseLoaderTimeoutException format:@"*** Operation timed out after %f seconds...", self.timeout]; + awaitingResponse = NO; + } + } } - (void)loadError:(NSError *)theError { awaitingResponse = NO; - successful = NO; + successful = NO; self.error = theError; } @@ -105,7 +105,7 @@ NSString * const RKTestResponseLoaderTimeoutException = @"RKTestResponseLoaderTi } - (void)request:(RKRequest *)request didLoadResponse:(RKResponse *)aResponse { - self.response = aResponse; + self.response = aResponse; // If request is an Object Loader, then objectLoader:didLoadObjects: // will be sent after didLoadResponse: @@ -133,15 +133,15 @@ NSString * const RKTestResponseLoaderTimeoutException = @"RKTestResponseLoaderTi } - (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; - awaitingResponse = NO; - successful = YES; + RKLogTrace(@"%@ Loaded response for %@ with body: %@", self, objectLoader, [objectLoader.response bodyAsString]); + RKLogDebug(@"%@ Loaded objects for %@: %@", self, objectLoader, objects); + self.objects = theObjects; + awaitingResponse = NO; + successful = YES; } - (void)objectLoader:(RKObjectLoader *)objectLoader didFailWithError:(NSError *)theError { - [self loadError:theError]; + [self loadError:theError]; } - (void)objectLoaderDidLoadUnexpectedResponse:(RKObjectLoader *)objectLoader { diff --git a/Code/UI/RKAbstractTableController.h b/Code/UI/RKAbstractTableController.h index c30c1240..cac5699f 100755 --- a/Code/UI/RKAbstractTableController.h +++ b/Code/UI/RKAbstractTableController.h @@ -226,11 +226,11 @@ extern NSString* const RKTableControllerDidBecomeOffline; @property (nonatomic, readonly) NSUInteger rowCount; /** Returns the section at the specified index. - * @param index Must be less than the total number of sections. */ + * @param index Must be less than the total number of sections. */ - (RKTableSection *)sectionAtIndex:(NSUInteger)index; /** Returns the first section with the specified header title. - * @param title The header title. */ + * @param title The header title. */ - (RKTableSection *)sectionWithHeaderTitle:(NSString *)title; /** @@ -244,8 +244,8 @@ extern NSString* const RKTableControllerDidBecomeOffline; - (NSUInteger)numberOfRowsInSectionAtIndex:(NSUInteger)index; /** Returns the index of the specified section. - * @param section Must be a valid non nil RKTableViewSection. - * @return If section is not found, method returns NSNotFound. */ + * @param section Must be a valid non nil RKTableViewSection. + * @return If section is not found, method returns NSNotFound. */ - (NSUInteger)indexForSection:(RKTableSection *)section; /** Returns the UITableViewCell created by applying the specified diff --git a/Code/UI/RKAbstractTableController.m b/Code/UI/RKAbstractTableController.m index f58cb73b..d5d67357 100755 --- a/Code/UI/RKAbstractTableController.m +++ b/Code/UI/RKAbstractTableController.m @@ -1079,8 +1079,8 @@ static NSString* lastUpdatedDateDictionaryKey = @"lastUpdatedDateDictionaryKey"; } - (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]; + // 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 { diff --git a/Code/UI/RKFetchedResultsTableController.m b/Code/UI/RKFetchedResultsTableController.m index 25e47c0d..8d8c89f9 100755 --- a/Code/UI/RKFetchedResultsTableController.m +++ b/Code/UI/RKFetchedResultsTableController.m @@ -51,9 +51,9 @@ @synthesize fetchRequest = _fetchRequest; - (void)dealloc { - _fetchedResultsController.delegate = nil; - [_fetchedResultsController release]; - _fetchedResultsController = nil; + _fetchedResultsController.delegate = nil; + [_fetchedResultsController release]; + _fetchedResultsController = nil; [_resourcePath release]; _resourcePath = nil; [_predicate release]; @@ -207,7 +207,7 @@ #pragma mark - Public - (NSFetchRequest *)fetchRequest { - return _fetchRequest ? _fetchRequest : _fetchedResultsController.fetchRequest; + return _fetchRequest ? _fetchRequest : _fetchedResultsController.fetchRequest; } - (void)loadTable { @@ -286,13 +286,13 @@ 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."); - self.objectLoader.objectMapping = [self.objectManager.mappingProvider objectMappingForClass:objectClass]; + self.objectLoader.objectMapping = [self.objectManager.mappingProvider objectMappingForClass:objectClass]; } #pragma mark - Managing Sections - (NSUInteger)sectionCount { - return [[_fetchedResultsController sections] count]; + return [[_fetchedResultsController sections] count]; } - (NSUInteger)rowCount { @@ -352,7 +352,7 @@ - (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]; + return [[_fetchedResultsController sections] count]; } - (NSInteger)tableView:(UITableView*)theTableView numberOfRowsInSection:(NSInteger)section { @@ -382,43 +382,43 @@ } - (NSArray*)sectionIndexTitlesForTableView:(UITableView*)theTableView { - if (theTableView.style == UITableViewStylePlain && self.showsSectionIndexTitles) { - return [_fetchedResultsController sectionIndexTitles]; - } - return nil; + if (theTableView.style == UITableViewStylePlain && self.showsSectionIndexTitles) { + return [_fetchedResultsController sectionIndexTitles]; + } + return nil; } - (NSInteger)tableView:(UITableView*)theTableView sectionForSectionIndexTitle:(NSString*)title atIndex:(NSInteger)index { - if (theTableView.style == UITableViewStylePlain && self.showsSectionIndexTitles) { - return [_fetchedResultsController sectionForSectionIndexTitle:title atIndex:index]; - } - return 0; + if (theTableView.style == UITableViewStylePlain && self.showsSectionIndexTitles) { + return [_fetchedResultsController sectionForSectionIndexTitle:title atIndex:index]; + } + return 0; } - (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) { + if (self.canEditRows && editingStyle == UITableViewCellEditingStyleDelete) { 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; + RKObjectMapping* mapping = [[RKObjectManager sharedManager].mappingProvider objectMappingForClass:[managedObject class]]; + if ([mapping isKindOfClass:[RKManagedObjectMapping class]]) { + RKManagedObjectMapping* managedObjectMapping = (RKManagedObjectMapping*)mapping; + NSString* primaryKeyAttribute = managedObjectMapping.primaryKeyAttribute; - if ([managedObject valueForKeyPath:primaryKeyAttribute]) { + if ([managedObject valueForKeyPath:primaryKeyAttribute]) { RKLogTrace(@"About to fire a delete request for managedObject: %@", managedObject); - [[RKObjectManager sharedManager] deleteObject:managedObject delegate:self]; - } else { + [[RKObjectManager sharedManager] deleteObject:managedObject delegate:self]; + } else { RKLogTrace(@"About to locally delete managedObject: %@", managedObject); - [managedObject.managedObjectContext deleteObject:managedObject]; + [managedObject.managedObjectContext deleteObject:managedObject]; NSError* error = nil; [managedObject.managedObjectContext save:&error]; if (error) { RKLogError(@"Failed to save managedObjectContext after a delete with error: %@", error); } - } - } - } + } + } + } } - (void)tableView:(UITableView*)theTableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destIndexPath { @@ -519,33 +519,33 @@ - (void)controller:(NSFetchedResultsController*)controller didChangeSection:(id)sectionInfo - atIndex:(NSUInteger)sectionIndex + atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type { if(_sortSelector) return; switch (type) { - case NSFetchedResultsChangeInsert: + case NSFetchedResultsChangeInsert: [self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade]; - break; + break; - case NSFetchedResultsChangeDelete: + case NSFetchedResultsChangeDelete: [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade]; - break; + break; - default: - RKLogTrace(@"Encountered unexpected section changeType: %d", type); - break; - } + default: + RKLogTrace(@"Encountered unexpected section changeType: %d", type); + break; + } } - (void)controller:(NSFetchedResultsController*)controller didChangeObject:(id)anObject - atIndexPath:(NSIndexPath *)indexPath + atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type - newIndexPath:(NSIndexPath *)newIndexPath { + newIndexPath:(NSIndexPath *)newIndexPath { if(_sortSelector) return; @@ -578,10 +578,10 @@ withRowAnimation:UITableViewRowAnimationFade]; break; - default: - RKLogTrace(@"Encountered unexpected object changeType: %d", type); - break; - } + default: + RKLogTrace(@"Encountered unexpected object changeType: %d", type); + break; + } } - (void)controllerDidChangeContent:(NSFetchedResultsController*)controller { diff --git a/Code/UI/RKTableController.h b/Code/UI/RKTableController.h index 8fe33d76..a6b11450 100644 --- a/Code/UI/RKTableController.h +++ b/Code/UI/RKTableController.h @@ -113,21 +113,21 @@ - (void)updateTableViewUsingBlock:(void (^)())block; /** Adds a new section to the model. - * @param section Must be a valid non nil RKTableViewSection. */ + * @param section Must be a valid non nil RKTableViewSection. */ // NOTE: connects cellMappings if section.cellMappings is nil... - (void)addSection:(RKTableSection *)section; /** Inserts a new section at the specified index. - * @param section Must be a valid non nil RKTableViewSection. - * @param index Must be less than the total number of sections. */ + * @param section Must be a valid non nil RKTableViewSection. + * @param index Must be less than the total number of sections. */ - (void)insertSection:(RKTableSection *)section atIndex:(NSUInteger)index; /** Removes the specified section from the model. - * @param section The section to remove. */ + * @param section The section to remove. */ - (void)removeSection:(RKTableSection *)section; /** Removes the section at the specified index from the model. - * @param index Must be less than the total number of section. */ + * @param index Must be less than the total number of section. */ - (void)removeSectionAtIndex:(NSUInteger)index; /** Removes all sections from the model. */ diff --git a/Code/UI/RKTableItem.m b/Code/UI/RKTableItem.m index 56eacb0f..63ed6f25 100644 --- a/Code/UI/RKTableItem.m +++ b/Code/UI/RKTableItem.m @@ -33,7 +33,7 @@ + (NSArray*)tableItemsFromStrings:(NSString*)firstString, ... { va_list args; va_start(args, firstString); - NSMutableArray* tableItems = [NSMutableArray array]; + NSMutableArray* tableItems = [NSMutableArray array]; for (NSString* string = firstString; string != nil; string = va_arg(args, NSString*)) { RKTableItem* tableItem = [RKTableItem new]; tableItem.text = string; diff --git a/Examples/RKTwitter/Classes/RKTStatus.h b/Examples/RKTwitter/Classes/RKTStatus.h index 750a01ea..a3c23afe 100644 --- a/Examples/RKTwitter/Classes/RKTStatus.h +++ b/Examples/RKTwitter/Classes/RKTStatus.h @@ -9,13 +9,13 @@ #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; } /** diff --git a/Examples/RKTwitter/Classes/RKTStatus.m b/Examples/RKTwitter/Classes/RKTStatus.m index c4dd0f86..0bbf4645 100644 --- a/Examples/RKTwitter/Classes/RKTStatus.m +++ b/Examples/RKTwitter/Classes/RKTStatus.m @@ -19,13 +19,13 @@ @synthesize user = _user; - (NSString*)description { - return [NSString stringWithFormat:@"%@ (ID: %@)", self.text, self.statusID]; + return [NSString stringWithFormat:@"%@ (ID: %@)", self.text, self.statusID]; } - (void)dealloc { [_statusID release]; - [_createdAt release]; - [_text release]; + [_createdAt release]; + [_text release]; [_urlString release]; [_inReplyToScreenName release]; [_user release]; diff --git a/Examples/RKTwitter/Classes/RKTUser.h b/Examples/RKTwitter/Classes/RKTUser.h index b2a1d042..20a6508b 100644 --- a/Examples/RKTwitter/Classes/RKTUser.h +++ b/Examples/RKTwitter/Classes/RKTUser.h @@ -7,9 +7,9 @@ // @interface RKTUser : NSObject { - NSNumber* _userID; - NSString* _name; - NSString* _screenName; + NSNumber* _userID; + NSString* _name; + NSString* _screenName; } @property (nonatomic, retain) NSNumber* userID; diff --git a/Examples/RKTwitter/Classes/RKTUser.m b/Examples/RKTwitter/Classes/RKTUser.m index 8ea569fb..aabd1d5f 100644 --- a/Examples/RKTwitter/Classes/RKTUser.m +++ b/Examples/RKTwitter/Classes/RKTUser.m @@ -16,8 +16,8 @@ - (void)dealloc { [_userID release]; - [_name release]; - [_screenName release]; + [_name release]; + [_screenName release]; [super dealloc]; } diff --git a/Examples/RKTwitter/Classes/RKTwitterAppDelegate.m b/Examples/RKTwitter/Classes/RKTwitterAppDelegate.m index 84a6bd3c..7fa71dbe 100644 --- a/Examples/RKTwitter/Classes/RKTwitterAppDelegate.m +++ b/Examples/RKTwitter/Classes/RKTwitterAppDelegate.m @@ -22,7 +22,7 @@ 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; @@ -44,7 +44,7 @@ [statusMapping mapRelationship:@"user" withMapping:userMapping]; // Update date format so that we can parse Twitter dates properly - // Wed Sep 29 15:31:08 +0000 2010 + // Wed Sep 29 15:31:08 +0000 2010 [RKObjectMapping addDefaultDateFormatterForString:@"E MMM d HH:mm:ss Z y" inTimeZone:nil]; // Uncomment these lines to use XML, comment it to use JSON @@ -55,9 +55,9 @@ [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]; diff --git a/Examples/RKTwitter/Classes/RKTwitterViewController.h b/Examples/RKTwitter/Classes/RKTwitterViewController.h index cc492beb..19abdbbf 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 9929afd2..6e985a9b 100644 --- a/Examples/RKTwitter/Classes/RKTwitterViewController.m +++ b/Examples/RKTwitter/Classes/RKTwitterViewController.m @@ -25,30 +25,30 @@ - (void)loadView { [super loadView]; - // Setup View and Table View - self.title = @"RestKit Tweets"; + // Setup View and Table View + self.title = @"RestKit Tweets"; [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleBlackTranslucent; self.navigationController.navigationBar.tintColor = [UIColor blackColor]; - self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(loadTimeline)] autorelease]; + self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(loadTimeline)] autorelease]; - UIImageView* imageView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"BG.png"]] autorelease]; - imageView.frame = CGRectOffset(imageView.frame, 0, -64); + UIImageView* imageView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"BG.png"]] autorelease]; + imageView.frame = CGRectOffset(imageView.frame, 0, -64); - [self.view insertSubview:imageView atIndex:0]; + [self.view insertSubview:imageView atIndex:0]; - _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 480-64) style:UITableViewStylePlain]; - _tableView.dataSource = self; - _tableView.delegate = self; - _tableView.backgroundColor = [UIColor clearColor]; - _tableView.separatorStyle = UITableViewCellSeparatorStyleNone; + _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 480-64) style:UITableViewStylePlain]; + _tableView.dataSource = self; + _tableView.delegate = self; + _tableView.backgroundColor = [UIColor clearColor]; + _tableView.separatorStyle = UITableViewCellSeparatorStyleNone; [self.view addSubview:_tableView]; - [self loadTimeline]; + [self loadTimeline]; } - (void)dealloc { - [_tableView release]; - [_statuses release]; + [_tableView release]; + [_statuses release]; [super dealloc]; } @@ -59,43 +59,43 @@ } - (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObjects:(NSArray*)objects { - NSLog(@"Loaded statuses: %@", objects); - [_statuses release]; - _statuses = [objects retain]; - [_tableView reloadData]; + 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]; - [alert show]; - NSLog(@"Hit error: %@", 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 { - CGSize size = [[[_statuses objectAtIndex:indexPath.row] text] sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(300, 9000)]; - return size.height + 10; + 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 { - return [_statuses count]; + return [_statuses count]; } - (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]; - cell.textLabel.numberOfLines = 0; - cell.textLabel.backgroundColor = [UIColor clearColor]; - cell.contentView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"listbg.png"]]; - } - cell.textLabel.text = [[_statuses objectAtIndex:indexPath.row] text]; - return cell; + 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]; + cell.textLabel.numberOfLines = 0; + cell.textLabel.backgroundColor = [UIColor clearColor]; + cell.contentView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"listbg.png"]]; + } + cell.textLabel.text = [[_statuses objectAtIndex:indexPath.row] text]; + return cell; } @end diff --git a/Examples/RKTwitterCoreData/Classes/RKTwitterAppDelegate.m b/Examples/RKTwitterCoreData/Classes/RKTwitterAppDelegate.m index 12446cf6..bd2802a4 100644 --- a/Examples/RKTwitterCoreData/Classes/RKTwitterAppDelegate.m +++ b/Examples/RKTwitterCoreData/Classes/RKTwitterAppDelegate.m @@ -19,7 +19,7 @@ - (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; @@ -64,7 +64,7 @@ [statusMapping mapRelationship:@"user" withMapping:userMapping]; // Update date format so that we can parse Twitter dates properly - // Wed Sep 29 15:31:08 +0000 2010 + // Wed Sep 29 15:31:08 +0000 2010 [RKObjectMapping addDefaultDateFormatterForString:@"E MMM d HH:mm:ss Z y" inTimeZone:nil]; // Register our mappings with the provider @@ -99,9 +99,9 @@ #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]; diff --git a/Examples/RKTwitterCoreData/Classes/RKTwitterViewController.h b/Examples/RKTwitterCoreData/Classes/RKTwitterViewController.h index 775e860f..909f4652 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 95f15e02..e4eb73dd 100644 --- a/Examples/RKTwitterCoreData/Classes/RKTwitterViewController.m +++ b/Examples/RKTwitterCoreData/Classes/RKTwitterViewController.m @@ -14,40 +14,40 @@ - (void)loadView { [super loadView]; - // Setup View and Table View - self.title = @"RestKit Tweets"; + // Setup View and Table View + self.title = @"RestKit Tweets"; [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleBlackTranslucent; self.navigationController.navigationBar.tintColor = [UIColor blackColor]; - self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(reloadButtonWasPressed:)] autorelease]; + self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(reloadButtonWasPressed:)] autorelease]; - UIImageView* imageView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"BG.png"]] autorelease]; - imageView.frame = CGRectOffset(imageView.frame, 0, -64); + UIImageView* imageView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"BG.png"]] autorelease]; + imageView.frame = CGRectOffset(imageView.frame, 0, -64); - [self.view insertSubview:imageView atIndex:0]; + [self.view insertSubview:imageView atIndex:0]; - _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 480-64) style:UITableViewStylePlain]; - _tableView.dataSource = self; - _tableView.delegate = self; - _tableView.backgroundColor = [UIColor clearColor]; - _tableView.separatorStyle = UITableViewCellSeparatorStyleNone; + _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 480-64) style:UITableViewStylePlain]; + _tableView.dataSource = self; + _tableView.delegate = self; + _tableView.backgroundColor = [UIColor clearColor]; + _tableView.separatorStyle = UITableViewCellSeparatorStyleNone; [self.view addSubview:_tableView]; - // Load statuses from core data - [self loadObjectsFromDataStore]; + // Load statuses from core data + [self loadObjectsFromDataStore]; } - (void)dealloc { - [_tableView release]; - [_statuses release]; + [_tableView release]; + [_statuses release]; [super dealloc]; } - (void)loadObjectsFromDataStore { - [_statuses release]; - NSFetchRequest* request = [RKTStatus fetchRequest]; - NSSortDescriptor* descriptor = [NSSortDescriptor sortDescriptorWithKey:@"createdAt" ascending:NO]; - [request setSortDescriptors:[NSArray arrayWithObject:descriptor]]; - _statuses = [[RKTStatus objectsWithFetchRequest:request] retain]; + [_statuses release]; + NSFetchRequest* request = [RKTStatus fetchRequest]; + NSSortDescriptor* descriptor = [NSSortDescriptor sortDescriptorWithKey:@"createdAt" ascending:NO]; + [request setSortDescriptors:[NSArray arrayWithObject:descriptor]]; + _statuses = [[RKTStatus objectsWithFetchRequest:request] retain]; } - (void)loadData { @@ -57,64 +57,64 @@ } - (void)reloadButtonWasPressed:(id)sender { - // Load the object model via RestKit - [self loadData]; + // Load the object model via RestKit + [self loadData]; } #pragma mark RKObjectLoaderDelegate methods - (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObjects:(NSArray*)objects { - [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"LastUpdatedAt"]; - [[NSUserDefaults standardUserDefaults] synchronize]; - NSLog(@"Loaded statuses: %@", objects); - [self loadObjectsFromDataStore]; - [_tableView reloadData]; + [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"LastUpdatedAt"]; + [[NSUserDefaults standardUserDefaults] synchronize]; + NSLog(@"Loaded statuses: %@", objects); + [self loadObjectsFromDataStore]; + [_tableView reloadData]; } - (void)objectLoader:(RKObjectLoader*)objectLoader didFailWithError:(NSError*)error { - UIAlertView* alert = [[[UIAlertView alloc] initWithTitle:@"Error" + UIAlertView* alert = [[[UIAlertView alloc] initWithTitle:@"Error" message:[error localizedDescription] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease]; - [alert show]; - NSLog(@"Hit error: %@", error); + [alert show]; + NSLog(@"Hit error: %@", error); } #pragma mark UITableViewDelegate methods - (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; + 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 { - return [_statuses count]; + 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]; - if (nil == dateString) { - dateString = @"Never"; - } - return [NSString stringWithFormat:@"Last Load: %@", dateString]; + 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]; - if (nil == cell) { - cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier] autorelease]; - cell.textLabel.font = [UIFont systemFontOfSize:14]; - cell.textLabel.numberOfLines = 0; - cell.textLabel.backgroundColor = [UIColor clearColor]; - cell.contentView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"listbg.png"]]; - } + 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]; + cell.textLabel.numberOfLines = 0; + cell.textLabel.backgroundColor = [UIColor clearColor]; + cell.contentView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"listbg.png"]]; + } RKTStatus* status = [_statuses objectAtIndex:indexPath.row]; - cell.textLabel.text = status.text; - return cell; + cell.textLabel.text = status.text; + return cell; } @end diff --git a/Tests/Application/UI/RKTableControllerTest.m b/Tests/Application/UI/RKTableControllerTest.m index 81a6ad72..7c57f526 100644 --- a/Tests/Application/UI/RKTableControllerTest.m +++ b/Tests/Application/UI/RKTableControllerTest.m @@ -40,28 +40,28 @@ - (id)init { self = [super init]; - if (self) { - _timeout = 3; - _awaitingResponse = NO; + if (self) { + _timeout = 3; + _awaitingResponse = NO; _cancelled = NO; - } + } - return self; + return self; } - (void)waitForLoad { _awaitingResponse = YES; - NSDate* startDate = [NSDate date]; + NSDate* startDate = [NSDate date]; - while (_awaitingResponse) { + while (_awaitingResponse) { NSLog(@"Awaiting response = %d", _awaitingResponse); - [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; - if ([[NSDate date] timeIntervalSinceDate:startDate] > self.timeout) { + [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; + if ([[NSDate date] timeIntervalSinceDate:startDate] > self.timeout) { NSLog(@"%@: Timed out!!!", self); _awaitingResponse = NO; - [NSException raise:nil format:@"*** Operation timed out after %f seconds...", self.timeout]; - } - } + [NSException raise:nil format:@"*** Operation timed out after %f seconds...", self.timeout]; + } + } } #pragma RKTableControllerDelegate methods diff --git a/Tests/Logic/CoreData/RKManagedObjectThreadSafeInvocationTest.m b/Tests/Logic/CoreData/RKManagedObjectThreadSafeInvocationTest.m index 32c8c477..5066c476 100644 --- a/Tests/Logic/CoreData/RKManagedObjectThreadSafeInvocationTest.m +++ b/Tests/Logic/CoreData/RKManagedObjectThreadSafeInvocationTest.m @@ -128,8 +128,8 @@ [self performSelectorInBackground:@selector(createBackgroundObjects) withObject:nil]; while (_waiting) { - [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; - } + [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; + } } @end diff --git a/Tests/Logic/Network/RKClientTest.m b/Tests/Logic/Network/RKClientTest.m index b1e6b502..d5713b70 100644 --- a/Tests/Logic/Network/RKClientTest.m +++ b/Tests/Logic/Network/RKClientTest.m @@ -37,17 +37,17 @@ } - (void)testShouldDetectNetworkStatusWithAHostname { - RKClient* client = [RKClient clientWithBaseURLString:@"http://restkit.org"]; - [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.3]]; // Let the runloop cycle - RKReachabilityNetworkStatus status = [client.reachabilityObserver networkStatus]; - assertThatInt(status, is(equalToInt(RKReachabilityReachableViaWiFi))); + RKClient* client = [RKClient clientWithBaseURLString:@"http://restkit.org"]; + [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.3]]; // Let the runloop cycle + RKReachabilityNetworkStatus status = [client.reachabilityObserver networkStatus]; + assertThatInt(status, is(equalToInt(RKReachabilityReachableViaWiFi))); } - (void)testShouldDetectNetworkStatusWithAnIPAddressBaseName { - RKClient* client = [RKClient clientWithBaseURLString:@"http://173.45.234.197"]; - [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.3]]; // Let the runloop cycle - RKReachabilityNetworkStatus status = [client.reachabilityObserver networkStatus]; - assertThatInt(status, isNot(equalToInt(RKReachabilityIndeterminate))); + RKClient* client = [RKClient clientWithBaseURLString:@"http://173.45.234.197"]; + [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.3]]; // Let the runloop cycle + RKReachabilityNetworkStatus status = [client.reachabilityObserver networkStatus]; + assertThatInt(status, isNot(equalToInt(RKReachabilityIndeterminate))); } - (void)testShouldSetTheCachePolicyOfTheRequest { RKClient* client = [RKClient clientWithBaseURLString:@"http://restkit.org"]; @@ -60,7 +60,7 @@ RKClient* client = [RKClient clientWithBaseURLString:@"http://restkit.org"]; client.requestCache = [[[RKRequestCache alloc] init] autorelease]; RKRequest* request = [client requestWithResourcePath:@""]; - assertThat(request.cache, is(equalTo(client.requestCache))); + assertThat(request.cache, is(equalTo(client.requestCache))); } - (void)testShouldLoadPageWithNoContentTypeInformation { diff --git a/Tests/Logic/Network/RKParamsAttachmentTest.m b/Tests/Logic/Network/RKParamsAttachmentTest.m index bf325cea..c2639143 100644 --- a/Tests/Logic/Network/RKParamsAttachmentTest.m +++ b/Tests/Logic/Network/RKParamsAttachmentTest.m @@ -30,14 +30,14 @@ @implementation RKParamsAttachmentTest - (void)testShouldRaiseAnExceptionWhenTheAttachedFileDoesNotExist { - NSException* exception = nil; - @try { - [[RKParamsAttachment alloc] initWithName:@"woot" file:@"/this/is/an/invalid/path"]; - } - @catch (NSException* e) { - exception = e; - } - assertThat(exception, isNot(nilValue())); + NSException* exception = nil; + @try { + [[RKParamsAttachment alloc] initWithName:@"woot" file:@"/this/is/an/invalid/path"]; + } + @catch (NSException* e) { + exception = e; + } + assertThat(exception, isNot(nilValue())); } - (void)testShouldReturnAnMD5ForSimpleValues { diff --git a/Tests/Logic/Network/RKRequestTest.m b/Tests/Logic/Network/RKRequestTest.m index 63a3c152..fb4c6835 100644 --- a/Tests/Logic/Network/RKRequestTest.m +++ b/Tests/Logic/Network/RKRequestTest.m @@ -59,17 +59,17 @@ * `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"]; - [params setFile:filePath forParam:@"file"]; - [params setValue:@"this is the value" forParam:@"test"]; - request.method = RKRequestMethodPOST; - request.params = params; - RKResponse* response = [request sendSynchronously]; - assertThatInteger(response.statusCode, is(equalToInt(200))); + 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]; + assertThatInteger(response.statusCode, is(equalToInt(200))); } #pragma mark - Basics @@ -168,8 +168,8 @@ request.timeoutInterval = 1.0; #if TARGET_OS_IPHONE - (void)testShouldSendTheRequestWhenBackgroundPolicyIsRKRequestBackgroundPolicyNone { - NSURL* URL = [RKTestFactory baseURL]; - RKRequest* request = [[RKRequest alloc] initWithURL:URL]; + 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 @@ -320,9 +320,9 @@ request.timeoutInterval = 1.0; - (void)testShouldCacheTheRequestHeadersAndBodyIncludingOurOwnCustomTimestampHeader { NSString* baseURL = [RKTestFactory baseURLString]; NSString* cacheDirForClient = [NSString stringWithFormat:@"RKClientRequestCache-%@", - [[NSURL URLWithString:baseURL] host]]; - NSString* cachePath = [[RKDirectory cachesDirectory] - stringByAppendingPathComponent:cacheDirForClient]; + [[NSURL URLWithString:baseURL] host]]; + NSString* cachePath = [[RKDirectory cachesDirectory] + stringByAppendingPathComponent:cacheDirForClient]; RKRequestCache* cache = [[RKRequestCache alloc] initWithPath:cachePath storagePolicy:RKRequestCacheStoragePolicyPermanently]; [cache invalidateWithStoragePolicy:RKRequestCacheStoragePolicyPermanently]; @@ -346,9 +346,9 @@ request.timeoutInterval = 1.0; - (void)testShouldGenerateAUniqueCacheKeyBasedOnTheUrlTheMethodAndTheHTTPBody { NSString* baseURL = [RKTestFactory baseURLString]; NSString* cacheDirForClient = [NSString stringWithFormat:@"RKClientRequestCache-%@", - [[NSURL URLWithString:baseURL] host]]; - NSString* cachePath = [[RKDirectory cachesDirectory] - stringByAppendingPathComponent:cacheDirForClient]; + [[NSURL URLWithString:baseURL] host]]; + NSString* cachePath = [[RKDirectory cachesDirectory] + stringByAppendingPathComponent:cacheDirForClient]; RKRequestCache* cache = [[RKRequestCache alloc] initWithPath:cachePath storagePolicy:RKRequestCacheStoragePolicyPermanently]; [cache invalidateWithStoragePolicy:RKRequestCacheStoragePolicyPermanently]; @@ -371,9 +371,9 @@ request.timeoutInterval = 1.0; - (void)testShouldLoadFromCacheWhenWeRecieveA304 { NSString* baseURL = [RKTestFactory baseURLString]; NSString* cacheDirForClient = [NSString stringWithFormat:@"RKClientRequestCache-%@", - [[NSURL URLWithString:baseURL] host]]; - NSString* cachePath = [[RKDirectory cachesDirectory] - stringByAppendingPathComponent:cacheDirForClient]; + [[NSURL URLWithString:baseURL] host]]; + NSString* cachePath = [[RKDirectory cachesDirectory] + stringByAppendingPathComponent:cacheDirForClient]; RKRequestCache* cache = [[RKRequestCache alloc] initWithPath:cachePath storagePolicy:RKRequestCacheStoragePolicyPermanently]; [cache invalidateWithStoragePolicy:RKRequestCacheStoragePolicyPermanently]; @@ -411,9 +411,9 @@ request.timeoutInterval = 1.0; - (void)testShouldUpdateTheInternalCacheDateWhenWeRecieveA304 { NSString* baseURL = [RKTestFactory baseURLString]; NSString* cacheDirForClient = [NSString stringWithFormat:@"RKClientRequestCache-%@", - [[NSURL URLWithString:baseURL] host]]; - NSString* cachePath = [[RKDirectory cachesDirectory] - stringByAppendingPathComponent:cacheDirForClient]; + [[NSURL URLWithString:baseURL] host]]; + NSString* cachePath = [[RKDirectory cachesDirectory] + stringByAppendingPathComponent:cacheDirForClient]; RKRequestCache* cache = [[RKRequestCache alloc] initWithPath:cachePath storagePolicy:RKRequestCacheStoragePolicyPermanently]; [cache invalidateWithStoragePolicy:RKRequestCacheStoragePolicyPermanently]; @@ -458,9 +458,9 @@ request.timeoutInterval = 1.0; - (void)testShouldLoadFromTheCacheIfThereIsAnError { NSString* baseURL = [RKTestFactory baseURLString]; NSString* cacheDirForClient = [NSString stringWithFormat:@"RKClientRequestCache-%@", - [[NSURL URLWithString:baseURL] host]]; - NSString* cachePath = [[RKDirectory cachesDirectory] - stringByAppendingPathComponent:cacheDirForClient]; + [[NSURL URLWithString:baseURL] host]]; + NSString* cachePath = [[RKDirectory cachesDirectory] + stringByAppendingPathComponent:cacheDirForClient]; RKRequestCache* cache = [[RKRequestCache alloc] initWithPath:cachePath storagePolicy:RKRequestCacheStoragePolicyPermanently]; [cache invalidateWithStoragePolicy:RKRequestCacheStoragePolicyPermanently]; @@ -496,9 +496,9 @@ request.timeoutInterval = 1.0; - (void)testShouldLoadFromTheCacheIfWeAreWithinTheTimeout { NSString* baseURL = [RKTestFactory baseURLString]; NSString* cacheDirForClient = [NSString stringWithFormat:@"RKClientRequestCache-%@", - [[NSURL URLWithString:baseURL] host]]; - NSString* cachePath = [[RKDirectory cachesDirectory] - stringByAppendingPathComponent:cacheDirForClient]; + [[NSURL URLWithString:baseURL] host]]; + NSString* cachePath = [[RKDirectory cachesDirectory] + stringByAppendingPathComponent:cacheDirForClient]; RKRequestCache* cache = [[RKRequestCache alloc] initWithPath:cachePath storagePolicy:RKRequestCacheStoragePolicyPermanently]; [cache invalidateWithStoragePolicy:RKRequestCacheStoragePolicyPermanently]; @@ -560,9 +560,9 @@ request.timeoutInterval = 1.0; - (void)testShouldLoadFromTheCacheIfWeAreOffline { NSString* baseURL = [RKTestFactory baseURLString]; NSString* cacheDirForClient = [NSString stringWithFormat:@"RKClientRequestCache-%@", - [[NSURL URLWithString:baseURL] host]]; - NSString* cachePath = [[RKDirectory cachesDirectory] - stringByAppendingPathComponent:cacheDirForClient]; + [[NSURL URLWithString:baseURL] host]]; + NSString* cachePath = [[RKDirectory cachesDirectory] + stringByAppendingPathComponent:cacheDirForClient]; RKRequestCache* cache = [[RKRequestCache alloc] initWithPath:cachePath storagePolicy:RKRequestCacheStoragePolicyPermanently]; [cache invalidateWithStoragePolicy:RKRequestCacheStoragePolicyPermanently]; @@ -603,9 +603,9 @@ request.timeoutInterval = 1.0; - (void)testShouldCacheTheStatusCodeMIMETypeAndURL { NSString* baseURL = [RKTestFactory baseURLString]; NSString* cacheDirForClient = [NSString stringWithFormat:@"RKClientRequestCache-%@", - [[NSURL URLWithString:baseURL] host]]; - NSString* cachePath = [[RKDirectory cachesDirectory] - stringByAppendingPathComponent:cacheDirForClient]; + [[NSURL URLWithString:baseURL] host]]; + NSString* cachePath = [[RKDirectory cachesDirectory] + stringByAppendingPathComponent:cacheDirForClient]; RKRequestCache* cache = [[RKRequestCache alloc] initWithPath:cachePath storagePolicy:RKRequestCacheStoragePolicyPermanently]; @@ -794,9 +794,9 @@ request.timeoutInterval = 1.0; request.params = params; NSString* baseURL = [RKTestFactory baseURLString]; NSString* cacheDirForClient = [NSString stringWithFormat:@"RKClientRequestCache-%@", - [[NSURL URLWithString:baseURL] host]]; + [[NSURL URLWithString:baseURL] host]]; NSString* cachePath = [[RKDirectory cachesDirectory] - stringByAppendingPathComponent:cacheDirForClient]; + stringByAppendingPathComponent:cacheDirForClient]; RKRequestCache *requestCache = [[RKRequestCache alloc] initWithPath:cachePath storagePolicy:RKRequestCacheStoragePolicyForDurationOfSession]; NSString *requestCachePath = [requestCache pathForRequest:request]; NSArray *pathComponents = [requestCachePath pathComponents]; @@ -812,9 +812,9 @@ request.timeoutInterval = 1.0; request.method = RKRequestMethodDELETE; NSString* baseURL = [RKTestFactory baseURLString]; NSString* cacheDirForClient = [NSString stringWithFormat:@"RKClientRequestCache-%@", - [[NSURL URLWithString:baseURL] host]]; + [[NSURL URLWithString:baseURL] host]]; NSString* cachePath = [[RKDirectory cachesDirectory] - stringByAppendingPathComponent:cacheDirForClient]; + stringByAppendingPathComponent:cacheDirForClient]; RKRequestCache *requestCache = [[RKRequestCache alloc] initWithPath:cachePath storagePolicy:RKRequestCacheStoragePolicyForDurationOfSession]; NSString *requestCachePath = [requestCache pathForRequest:request]; assertThat(requestCachePath, is(nilValue())); diff --git a/Tests/Logic/Network/RKResponseTest.m b/Tests/Logic/Network/RKResponseTest.m index 1a86fc99..0ba76ba1 100644 --- a/Tests/Logic/Network/RKResponseTest.m +++ b/Tests/Logic/Network/RKResponseTest.m @@ -22,7 +22,7 @@ #import "RKResponse.h" @interface RKResponseTest : RKTestCase { - RKResponse* _response; + RKResponse* _response; } @end @@ -30,199 +30,199 @@ @implementation RKResponseTest - (void)setUp { - _response = [[RKResponse alloc] init]; + _response = [[RKResponse alloc] init]; } - (void)testShouldConsiderResponsesLessThanOneHudredOrGreaterThanSixHundredInvalid { - RKResponse* response = [[[RKResponse alloc] init] autorelease]; - id mock = [OCMockObject partialMockForObject:response]; - NSInteger statusCode = 99; - [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; - assertThatBool([mock isInvalid], is(equalToBool(YES))); - statusCode = 601; - [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; - assertThatBool([mock isInvalid], is(equalToBool(YES))); + RKResponse* response = [[[RKResponse alloc] init] autorelease]; + id mock = [OCMockObject partialMockForObject:response]; + NSInteger statusCode = 99; + [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; + assertThatBool([mock isInvalid], is(equalToBool(YES))); + statusCode = 601; + [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; + assertThatBool([mock isInvalid], is(equalToBool(YES))); } - (void)testShouldConsiderResponsesInTheOneHudredsInformational { - RKResponse* response = [[[RKResponse alloc] init] autorelease]; - id mock = [OCMockObject partialMockForObject:response]; - NSInteger statusCode = 100; - [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; - assertThatBool([mock isInformational], is(equalToBool(YES))); - statusCode = 199; - [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; - assertThatBool([mock isInformational], is(equalToBool(YES))); + RKResponse* response = [[[RKResponse alloc] init] autorelease]; + id mock = [OCMockObject partialMockForObject:response]; + NSInteger statusCode = 100; + [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; + assertThatBool([mock isInformational], is(equalToBool(YES))); + statusCode = 199; + [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; + assertThatBool([mock isInformational], is(equalToBool(YES))); } - (void)testShouldConsiderResponsesInTheTwoHundredsSuccessful { - RKResponse* response = [[[RKResponse alloc] init] autorelease]; - id mock = [OCMockObject partialMockForObject:response]; - NSInteger twoHundred = 200; - [[[mock stub] andReturnValue:OCMOCK_VALUE(twoHundred)] statusCode]; - assertThatBool([mock isSuccessful], is(equalToBool(YES))); - twoHundred = 299; - [[[mock stub] andReturnValue:OCMOCK_VALUE(twoHundred)] statusCode]; - assertThatBool([mock isSuccessful], is(equalToBool(YES))); + RKResponse* response = [[[RKResponse alloc] init] autorelease]; + id mock = [OCMockObject partialMockForObject:response]; + NSInteger twoHundred = 200; + [[[mock stub] andReturnValue:OCMOCK_VALUE(twoHundred)] statusCode]; + assertThatBool([mock isSuccessful], is(equalToBool(YES))); + twoHundred = 299; + [[[mock stub] andReturnValue:OCMOCK_VALUE(twoHundred)] statusCode]; + assertThatBool([mock isSuccessful], is(equalToBool(YES))); } - (void)testShouldConsiderResponsesInTheThreeHundredsRedirects { - RKResponse* response = [[[RKResponse alloc] init] autorelease]; - id mock = [OCMockObject partialMockForObject:response]; - NSInteger statusCode = 300; - [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; - assertThatBool([mock isRedirection], is(equalToBool(YES))); - statusCode = 399; - [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; - assertThatBool([mock isRedirection], is(equalToBool(YES))); + RKResponse* response = [[[RKResponse alloc] init] autorelease]; + id mock = [OCMockObject partialMockForObject:response]; + NSInteger statusCode = 300; + [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; + assertThatBool([mock isRedirection], is(equalToBool(YES))); + statusCode = 399; + [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; + assertThatBool([mock isRedirection], is(equalToBool(YES))); } - (void)testShouldConsiderResponsesInTheFourHundredsClientErrors { - RKResponse* response = [[[RKResponse alloc] init] autorelease]; - id mock = [OCMockObject partialMockForObject:response]; - NSInteger statusCode = 400; - [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; - assertThatBool([mock isClientError], is(equalToBool(YES))); - statusCode = 499; - [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; - assertThatBool([mock isClientError], is(equalToBool(YES))); + RKResponse* response = [[[RKResponse alloc] init] autorelease]; + id mock = [OCMockObject partialMockForObject:response]; + NSInteger statusCode = 400; + [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; + assertThatBool([mock isClientError], is(equalToBool(YES))); + statusCode = 499; + [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; + assertThatBool([mock isClientError], is(equalToBool(YES))); } - (void)testShouldConsiderResponsesInTheFiveHundredsServerErrors { - RKResponse* response = [[[RKResponse alloc] init] autorelease]; - id mock = [OCMockObject partialMockForObject:response]; - NSInteger statusCode = 500; - [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; - assertThatBool([mock isServerError], is(equalToBool(YES))); - statusCode = 599; - [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; - assertThatBool([mock isServerError], is(equalToBool(YES))); + RKResponse* response = [[[RKResponse alloc] init] autorelease]; + id mock = [OCMockObject partialMockForObject:response]; + NSInteger statusCode = 500; + [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; + assertThatBool([mock isServerError], is(equalToBool(YES))); + statusCode = 599; + [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; + assertThatBool([mock isServerError], is(equalToBool(YES))); } - (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))); + 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]; - id mock = [OCMockObject partialMockForObject:response]; - NSInteger statusCode = 201; - [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; - assertThatBool([mock isCreated], is(equalToBool(YES))); + 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]; - id mock = [OCMockObject partialMockForObject:response]; - NSInteger statusCode = 403; - [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; - assertThatBool([mock isForbidden], is(equalToBool(YES))); + 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]; - id mock = [OCMockObject partialMockForObject:response]; - NSInteger statusCode = 404; - [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; - assertThatBool([mock isNotFound], is(equalToBool(YES))); + 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]; - id mock = [OCMockObject partialMockForObject:response]; - NSInteger statusCode = 409; - [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; - assertThatBool([mock isConflict], is(equalToBool(YES))); + 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]; - id mock = [OCMockObject partialMockForObject:response]; - NSInteger statusCode = 410; - [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; - assertThatBool([mock isGone], is(equalToBool(YES))); + 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]; - id mock = [OCMockObject partialMockForObject:response]; - NSInteger statusCode = 301; - [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; - assertThatBool([mock isRedirect], is(equalToBool(YES))); - statusCode = 302; - [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; - assertThatBool([mock isRedirect], is(equalToBool(YES))); - statusCode = 303; - [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; - assertThatBool([mock isRedirect], is(equalToBool(YES))); - statusCode = 307; - [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; - assertThatBool([mock isRedirect], is(equalToBool(YES))); + RKResponse* response = [[[RKResponse alloc] init] autorelease]; + id mock = [OCMockObject partialMockForObject:response]; + NSInteger statusCode = 301; + [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; + assertThatBool([mock isRedirect], is(equalToBool(YES))); + statusCode = 302; + [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; + assertThatBool([mock isRedirect], is(equalToBool(YES))); + statusCode = 303; + [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; + assertThatBool([mock isRedirect], is(equalToBool(YES))); + statusCode = 307; + [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; + assertThatBool([mock isRedirect], is(equalToBool(YES))); } - (void)testShouldConsiderVariousResponsesEmpty { - RKResponse* response = [[[RKResponse alloc] init] autorelease]; - id mock = [OCMockObject partialMockForObject:response]; - NSInteger statusCode = 201; - [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; - assertThatBool([mock isEmpty], is(equalToBool(YES))); - statusCode = 204; - [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; - assertThatBool([mock isEmpty], is(equalToBool(YES))); - statusCode = 304; - [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; - assertThatBool([mock isEmpty], is(equalToBool(YES))); + RKResponse* response = [[[RKResponse alloc] init] autorelease]; + id mock = [OCMockObject partialMockForObject:response]; + NSInteger statusCode = 201; + [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; + assertThatBool([mock isEmpty], is(equalToBool(YES))); + statusCode = 204; + [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; + assertThatBool([mock isEmpty], is(equalToBool(YES))); + statusCode = 304; + [[[mock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode]; + assertThatBool([mock isEmpty], is(equalToBool(YES))); } - (void)testShouldMakeTheContentTypeHeaderAccessible { - RKResponse* response = [[[RKResponse alloc] init] autorelease]; - id mock = [OCMockObject partialMockForObject:response]; - NSDictionary* headers = [NSDictionary dictionaryWithObject:@"application/xml" forKey:@"Content-Type"]; - [[[mock stub] andReturn:headers] allHeaderFields]; - assertThat([mock contentType], is(equalTo(@"application/xml"))); + RKResponse* response = [[[RKResponse alloc] init] autorelease]; + id mock = [OCMockObject partialMockForObject:response]; + 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]; - id mock = [OCMockObject partialMockForObject:response]; - NSDictionary* headers = [NSDictionary dictionaryWithObject:@"12345" forKey:@"Content-Length"]; - [[[mock stub] andReturn:headers] allHeaderFields]; - assertThat([mock contentLength], is(equalTo(@"12345"))); + RKResponse* response = [[[RKResponse alloc] init] autorelease]; + id mock = [OCMockObject partialMockForObject:response]; + 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]; - id mock = [OCMockObject partialMockForObject:response]; - NSDictionary* headers = [NSDictionary dictionaryWithObject:@"/foo/bar" forKey:@"Location"]; - [[[mock stub] andReturn:headers] allHeaderFields]; - assertThat([mock location], is(equalTo(@"/foo/bar"))); + RKResponse* response = [[[RKResponse alloc] init] autorelease]; + id mock = [OCMockObject partialMockForObject:response]; + 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]; - id mock = [OCMockObject partialMockForObject:response]; - NSDictionary* headers = [NSDictionary dictionaryWithObject:@"application/xml" forKey:@"Content-Type"]; - [[[mock stub] andReturn:headers] allHeaderFields]; - assertThatBool([mock isXML], is(equalToBool(YES))); + RKResponse* response = [[[RKResponse alloc] init] autorelease]; + id mock = [OCMockObject partialMockForObject:response]; + 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]; - id mock = [OCMockObject partialMockForObject:response]; - NSDictionary* headers = [NSDictionary dictionaryWithObject:@"application/json" forKey:@"Content-Type"]; - [[[mock stub] andReturn:headers] allHeaderFields]; - assertThatBool([mock isJSON], is(equalToBool(YES))); + RKResponse* response = [[[RKResponse alloc] init] autorelease]; + id mock = [OCMockObject partialMockForObject:response]; + 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]; - id mock = [OCMockObject partialMockForObject:response]; - [[[mock stub] andReturn:@"sad;sdvjnk;"] bodyAsString]; + id mock = [OCMockObject partialMockForObject:response]; + [[[mock stub] andReturn:@"sad;sdvjnk;"] bodyAsString]; [[[mock stub] andReturn:@"application/json"] MIMEType]; NSError* error = nil; id object = [mock parsedBody:&error]; @@ -243,8 +243,8 @@ - (void)testShouldNotCrashWhenParserReturnsNilWithoutAnError { RKResponse* response = [[[RKResponse alloc] init] autorelease]; - id mockResponse = [OCMockObject partialMockForObject:response]; - [[[mockResponse stub] andReturn:@""] bodyAsString]; + 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]]; diff --git a/Tests/Logic/ObjectMapping/RKObjectManagerTest.m b/Tests/Logic/ObjectMapping/RKObjectManagerTest.m index c4cf0f39..b73435fd 100644 --- a/Tests/Logic/ObjectMapping/RKObjectManagerTest.m +++ b/Tests/Logic/ObjectMapping/RKObjectManagerTest.m @@ -29,7 +29,7 @@ #import "RKObjectMapperTestModel.h" @interface RKObjectManagerTest : RKTestCase { - RKObjectManager* _objectManager; + RKObjectManager* _objectManager; } @end @@ -40,7 +40,7 @@ [RKTestFactory setUp]; _objectManager = [RKTestFactory objectManager]; - _objectManager.objectStore = [RKManagedObjectStore objectStoreWithStoreFilename:@"RKTests.sqlite"]; + _objectManager.objectStore = [RKManagedObjectStore objectStoreWithStoreFilename:@"RKTests.sqlite"]; [RKObjectManager setSharedManager:_objectManager]; [_objectManager.objectStore deletePersistentStore]; @@ -88,7 +88,7 @@ - (void)testShouldSetTheAcceptHeaderAppropriatelyForTheFormat { - assertThat([_objectManager.client.HTTPHeaders valueForKey:@"Accept"], is(equalTo(@"application/json"))); + assertThat([_objectManager.client.HTTPHeaders valueForKey:@"Accept"], is(equalTo(@"application/json"))); } // TODO: Move to Core Data specific spec file... @@ -124,7 +124,7 @@ objectLoader.method = RKRequestMethodPOST; objectLoader.targetObject = temporaryHuman; objectLoader.serializationMapping = mapping; - [objectLoader send]; + [objectLoader send]; [loader waitForResponse]; assertThat(temporaryHuman.managedObjectContext, is(equalTo(nil))); @@ -146,7 +146,7 @@ objectLoader.method = RKRequestMethodPOST; objectLoader.targetObject = temporaryHuman; objectLoader.serializationMapping = mapping; - [objectLoader send]; + [objectLoader send]; [loader waitForResponse]; assertThat(temporaryHuman.managedObjectContext, is(equalTo(_objectManager.objectStore.primaryManagedObjectContext))); @@ -156,31 +156,31 @@ - (void)testShouldLoadAHuman { assertThatBool([RKClient sharedClient].isNetworkReachable, is(equalToBool(YES))); RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; - [_objectManager loadObjectsAtResourcePath:@"/JSON/humans/1.json" delegate:loader]; - [loader waitForResponse]; + [_objectManager loadObjectsAtResourcePath:@"/JSON/humans/1.json" delegate:loader]; + [loader waitForResponse]; assertThat(loader.error, is(nilValue())); assertThat(loader.objects, isNot(empty())); - RKHuman* blake = (RKHuman*)[loader.objects objectAtIndex:0]; - assertThat(blake.name, is(equalTo(@"Blake Watters"))); + RKHuman* blake = (RKHuman*)[loader.objects objectAtIndex:0]; + assertThat(blake.name, is(equalTo(@"Blake Watters"))); } - (void)testShouldLoadAllHumans { RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; - [_objectManager loadObjectsAtResourcePath:@"/JSON/humans/all.json" delegate:loader]; - [loader waitForResponse]; - NSArray* humans = (NSArray*) loader.objects; - assertThatUnsignedInteger([humans count], is(equalToInt(2))); - assertThat([humans objectAtIndex:0], is(instanceOf([RKHuman class]))); + [_objectManager loadObjectsAtResourcePath:@"/JSON/humans/all.json" delegate:loader]; + [loader waitForResponse]; + NSArray* humans = (NSArray*) loader.objects; + assertThatUnsignedInteger([humans count], is(equalToInt(2))); + assertThat([humans objectAtIndex:0], is(instanceOf([RKHuman class]))); } - (void)testShouldHandleConnectionFailures { - NSString* localBaseURL = [NSString stringWithFormat:@"http://127.0.0.1:3001"]; - RKObjectManager* modelManager = [RKObjectManager managerWithBaseURLString:localBaseURL]; + NSString* localBaseURL = [NSString stringWithFormat:@"http://127.0.0.1:3001"]; + RKObjectManager* modelManager = [RKObjectManager managerWithBaseURLString:localBaseURL]; modelManager.client.requestQueue.suspended = NO; RKTestResponseLoader* loader = [RKTestResponseLoader responseLoader]; - [modelManager loadObjectsAtResourcePath:@"/JSON/humans/1" delegate:loader]; - [loader waitForResponse]; - assertThatBool(loader.wasSuccessful, is(equalToBool(NO))); + [modelManager loadObjectsAtResourcePath:@"/JSON/humans/1" delegate:loader]; + [loader waitForResponse]; + assertThatBool(loader.wasSuccessful, is(equalToBool(NO))); } - (void)testShouldPOSTAnObject { diff --git a/Tests/Logic/ObjectMapping/RKObjectMappingProviderTest.m b/Tests/Logic/ObjectMapping/RKObjectMappingProviderTest.m index b9fb7cf6..2f7f0fba 100644 --- a/Tests/Logic/ObjectMapping/RKObjectMappingProviderTest.m +++ b/Tests/Logic/ObjectMapping/RKObjectMappingProviderTest.m @@ -31,7 +31,7 @@ #import "RKOrderedDictionary.h" @interface RKObjectMappingProviderTest : RKTestCase { - RKObjectManager* _objectManager; + RKObjectManager* _objectManager; } @end @@ -40,7 +40,7 @@ - (void)setUp { _objectManager = [RKTestFactory objectManager]; - _objectManager.objectStore = [RKManagedObjectStore objectStoreWithStoreFilename:@"RKTests.sqlite"]; + _objectManager.objectStore = [RKManagedObjectStore objectStoreWithStoreFilename:@"RKTests.sqlite"]; [RKObjectManager setSharedManager:_objectManager]; [_objectManager.objectStore deletePersistentStore]; } diff --git a/Tests/Logic/ObjectMapping/RKObjectPaginatorTest.m b/Tests/Logic/ObjectMapping/RKObjectPaginatorTest.m index befbb950..09b0b16e 100644 --- a/Tests/Logic/ObjectMapping/RKObjectPaginatorTest.m +++ b/Tests/Logic/ObjectMapping/RKObjectPaginatorTest.m @@ -88,15 +88,15 @@ NSString * const RKTestPaginatorDelegateTimeoutException = @"RKTestPaginatorDele self.paginatedObjects = nil; self.paginationError = nil; - NSDate* startDate = [NSDate date]; + NSDate* startDate = [NSDate date]; - while (loading) { - [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; - if ([[NSDate date] timeIntervalSinceDate:startDate] > self.timeout) { - [NSException raise:@"RKTestPaginatorDelegateTimeoutException" format:@"*** Operation timed out after %f seconds...", self.timeout]; - loading = NO; - } - } + while (loading) { + [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; + if ([[NSDate date] timeIntervalSinceDate:startDate] > self.timeout) { + [NSException raise:@"RKTestPaginatorDelegateTimeoutException" format:@"*** Operation timed out after %f seconds...", self.timeout]; + loading = NO; + } + } } #pragma mark - RKObjectPaginatorDelegate diff --git a/Tests/Models/RKHuman.m b/Tests/Models/RKHuman.m index 2e48a55d..e4d175a8 100644 --- a/Tests/Models/RKHuman.m +++ b/Tests/Models/RKHuman.m @@ -40,7 +40,7 @@ @dynamic catsInOrderByAge; - (NSString*)polymorphicResourcePath { - return @"/this/is/the/path"; + return @"/this/is/the/path"; } @end diff --git a/Tests/Models/RKMappableAssociation.h b/Tests/Models/RKMappableAssociation.h index 4c0ee9ce..3a41f096 100644 --- a/Tests/Models/RKMappableAssociation.h +++ b/Tests/Models/RKMappableAssociation.h @@ -21,7 +21,7 @@ #import @interface RKMappableAssociation : NSObject { - NSString* _testString; + NSString* _testString; NSDate* _date; } diff --git a/Tests/Models/RKMappableObject.h b/Tests/Models/RKMappableObject.h index 4c40a3ec..7abc4cb3 100644 --- a/Tests/Models/RKMappableObject.h +++ b/Tests/Models/RKMappableObject.h @@ -22,12 +22,12 @@ #import "RKMappableAssociation.h" @interface RKMappableObject : NSObject { - NSDate* _dateTest; - NSNumber* _numberTest; - NSString* _stringTest; + NSDate* _dateTest; + NSNumber* _numberTest; + NSString* _stringTest; NSURL* _urlTest; - RKMappableAssociation* _hasOne; - NSSet* _hasMany; + RKMappableAssociation* _hasOne; + NSSet* _hasMany; } @property (nonatomic, retain) NSDate* dateTest; diff --git a/Tests/Models/RKObjectMapperTestModel.h b/Tests/Models/RKObjectMapperTestModel.h index 9502e2da..c77b42d5 100644 --- a/Tests/Models/RKObjectMapperTestModel.h +++ b/Tests/Models/RKObjectMapperTestModel.h @@ -22,9 +22,9 @@ #import @interface RKObjectMapperTestModel : NSObject { - NSString* _name; - NSNumber* _age; - NSDate* _createdAt; + NSString* _name; + NSNumber* _age; + NSDate* _createdAt; } @property (nonatomic,retain) NSString* name;