Tuesday, May 7, 2013

NSCache setEvictsObjectsWithDiscardedContent example ios


setEvictsObjectsWithDiscardedContent:

Sets whether the cache will automatically evict NSDiscardableContent objects after the object’s content has been discarded.
- (void)setEvictsObjectsWithDiscardedContent:(BOOL)b
Parameters
b
If YES, the cache evicts NSDiscardableContent objects after the object’s contents has been discarded; if NO the cache does not evict these objects.

Example of [NSCache setEvictsObjectsWithDiscardedContent]
   _cellCache = [[NSCache alloc] init];
   [_cellCache setDelegate:self];
   [_cellCache setEvictsObjectsWithDiscardedContent :NO];

NSCache setCountLimit example ios


setCountLimit:

Sets the maximum number of objects that the cache can hold.
- (void)setCountLimit:(NSUInteger)lim
Parameters
lim
The maximum number of objects that the cache will be allowed to hold.
Discussion of [NSCache setCountLimit]
Setting the count limit to a number less than or equal to 0 will have no effect on the maximum size of the cache.

Example of [NSCache setCountLimit]
cache = [[NSCache alloc] init];
[cache setCountLimit:100];
[cache setTotalCostLimit:1500000];
[cache setEvictsObjectsWithDiscardedContent:YES];

Example of [NSCache setCountLimit]
+(NSCache*)sharedCache;
{
    static NSCache* sharedCache = nil;
    if (sharedCache == nil) {
        sharedCache = [[[self alloc] init] retain];
        [sharedCache setCountLimit:100];
    }
    return sharedCache;
}

NSCache objectForKey example ios


objectForKey:

Returns the value associated with a given key.
- (id)objectForKey:(id)key
Parameters
key
An object identifying the value.
Return Value of [NSCache objectForKey]
The value associated with key, or NULL if no value is associated with key. The caller does not have to release the value returned to it.
Example of [NSCache objectForKey]
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:1 inSection:1];
 NSString *res = [cache objectForKey :indexPath];
 if (!res) {                      
     res=@"1";
     [cache setObject:res forKey:indexPath];
 }
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:1 inSection:1];
NSLog(@"%@",[cache objectForKey:indexPath]);
Example of [NSCache objectForKey]
// Your cache should have a lifetime beyond the method or handful of methods
// that use it. For example, you could make it a field of your application
// delegate, or of your view controller, or something like that. Up to you.
NSCache *myCache = ...;
NSAssert(myCache != nil, @"cache object is missing");

// Try to get the existing object out of the cache, if it's there.
Widget *myWidget = [myCache objectForKey: @"Important Widget"];
if (!myWidget) {
    // It's not in the cache yet, or has been removed. We have to
    // create it. Presumably, creation is an expensive operation,
    // which is why we cache the results. If creation is cheap, we
    // probably don't need to bother caching it. That's a design
    // decision you'll have to make yourself.
    myWidget = [[[Widget alloc] initExpensively] autorelease];

    // Put it in the cache. It will stay there as long as the OS
    // has room for it. It may be removed at any time, however,
    // at which point we'll have to create it again on next use.
    [myCache setObject: myWidget forKey: @"Important Widget"];
}

// myWidget should exist now either way. Use it here.
if (myWidget) {
    [myWidget runOrWhatever];
}

NSCache evictsObjectsWithDiscardedContent example ios


evictsObjectsWithDiscardedContent

Returns whether or not the cache will automatically evict discardable-content objects whose content has been discarded.
- (BOOL)evictsObjectsWithDiscardedContent
Return Value of [NSCache evictsObjectsWithDiscardedContent]
YES if the cache will evict the object after it is discarded; otherwise, NO.
Discussion
By default, evictsObjectsWithDiscardedContent is set to YES.
Example of [NSCache evictsObjectsWithDiscardedContent]
   _cellCache = [[NSCache alloc] init];
   [_cellCache setDelegate:self];
   [_cellCache setEvictsObjectsWithDiscardedContent:NO];

NSCache countLimit example ios


countLimit

Returns the maximum number of objects that the cache can currently hold.
- (NSUInteger)countLimit
Return Value
The maximum number of objects that the cache can currently hold.
Discussion of [NSCache countLimit]
By default, countLimit will be set to 0. Any countLimit less than or equal to 0 has no effect on the number of allowed entries in the cache. This limit is not a strict limit, and if the cache goes over the limit, an object in the cache could be evicted instantly, later, or possibly never, all depending on the implementation details of the cache.
Example of [NSCache countLimit]


- (NSCache *)imageCache {

    if (!_imageCache) {
        _imageCache = [[NSCache alloc] init];
        _imageCache.countLimit = kIMAGE_REQUEST_CACHE_LIMIT;
    }
    return _imageCache;
}
Example of [NSCache countLimit]
-(UIImage *)buscarEnCache:(UsersController *)auxiliarStruct{
    UIImage *image;

    NSLog(@"cache: %i", [cache countLimit]);
    if ([cache countLimit] > 0) {
        if ([cache objectForKey:auxiliarStruct.thumb]){    
            image = [cache objectForKey:auxiliarStruct.thumb];
        }else{ //IF isnt't cached, is saved
            NSString *imageURLString = [NSString stringWithFormat:@"http://mydomain.com/%@",auxiliarStruct.thumb];
            NSURL *imageURL = [NSURL URLWithString:imageURLString];
            NSData * imageData = [NSData dataWithContentsOfURL:imageURL];
            image = [UIImage imageWithData:imageData];
            [cache setObject:image forKey:auxiliarStruct.thumb];
        }        
    }else{ 
        NSString *imageURLString = [NSString stringWithFormat:@"http://mydomain.com/%@",auxiliarStruct.thumb];
        NSURL *imageURL = [NSURL URLWithString:imageURLString];
        NSData * imageData = [NSData dataWithContentsOfURL:imageURL];
        image = [UIImage imageWithData:imageData];
        [cache setObject:image forKey:auxiliarStruct.thumb];
    }
    return image;
}

Monday, May 6, 2013

NSBlockOperation addExecutionBlock example ios


addExecutionBlock:

Adds the specified block to the receiver’s list of blocks to perform.
- (void)addExecutionBlock:(void (^)(void))block
Parameters
block
The block to add to the receiver’s list. The block should take no parameters and have no return value.
Discussion of [NSBlockOperation addExecutionBlock]
The specified block should not make any assumptions about its execution environment.
Calling this method while the receiver is executing or has already finished causes anNSInvalidArgumentException exception to be thrown.
Example of [NSBlockOperation addExecutionBlock]
NSBlockOperation *operation = [[NSBlockOperation alloc] init];
__weak NSBlockOperation *weakOperation = operation;
[operation addExecutionBlock:^{
   while( ! [weakOperation isCancelled]){
      //do something...
   }
}];
Example of [NSBlockOperation addExecutionBlock]
NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
[operationQueue setMaxConcurrentOperationCount: 1];

NSBlockOperation *operation = [[NSBlockOperation alloc] init];
__weak NSBlockOperation *weakOperation = operation;
[operation addExecutionBlock: ^ {
    for (unsigned i=0; i < 10000000; i++) {
        if ([weakOperation isCancelled]) return;
        printf("%i\n",i);
    }
}];
[operationQueue addOperation:operation];

sleep(1);

if ([operationQueue operationCount] > 0) {
    [operationQueue cancelAllOperations];
}

NSBlockOperation blockOperationWithBlock example ios


blockOperationWithBlock:

Creates and returns an NSBlockOperation object and adds the specified block to it.
+ (id)blockOperationWithBlock:(void (^)(void))block
Parameters
block
The block to add to the new block operation object’s list. The block should take no parameters and have no return value.
Return Value of [NSBlockOperation blockOperationWithBlock]
A new block operation object.
Example of [NSBlockOperation blockOperationWithBlock]
- (NSOperation *)executeBlock:(void (^)(void))block inQueue:(NSOperationQueue *)queue completion:(void (^)(BOOL finished))completion {

    NSOperation *blockOperation = [NSBlockOperation blockOperationWithBlock :block];
    NSOperation *completionOperation = [NSBlockOperation blockOperationWithBlock:^{
        completion(blockOperation.isFinished);
    }];
    [completionOperation addDependency:blockOperation];

    [[NSOperationQueue currentQueue] addOperation:completionOperation];
    [queue addOperation:blockOperation];
    return blockOperation;
}

- (void)testIt {

    backgroundOperationQueue = [[NSOperationQueue alloc] init];

    NSMutableString *string = [NSMutableString stringWithString:@"tea"];
    NSString *otherString = @"for";

    NSOperation *operation = [self executeBlock:^{
        NSString *yetAnother = @"two";
        [string appendFormat:@" %@ %@", otherString, yetAnother];
    } completion:^(BOOL finished) {
        // this logs "tea for two"
        NSLog(@"%@", string);
    }];

    NSLog(@"keep this operation so we can cancel it: %@", operation);
}
Example of [NSBlockOperation blockOperationWithBlock]
_requestA = [NSBlockOperation blockOperationWithBlock:^{
    // Normal requestA code here.
    // ...

    // Assuming you create all requestA and requestB instances on the main thread...
    dispatch_async(dispatch_get_main_queue(), ^{ _requestA = nil; });
}];