Streamlyne / Cocoa-SDK

Streamlyne API for Cocoa Developers
https://github.com/Streamlyne/Cocoa-SDK
2 stars 1 forks source link

Cache Attribute's Computed Query for it's parent Asset #15

Closed Glavin001 closed 10 years ago

Glavin001 commented 10 years ago

See https://github.com/Streamlyne/Cocoa-SDK/blob/master/Common/Models/SLAttribute.m#L38-L58

Glavin001 commented 10 years ago

See http://stackoverflow.com/a/145164 for singleton in Objective-C.

Glavin001 commented 10 years ago

Tested the following and it works wonders!


- (PMKPromise *) asset
{
    static PMKPromise *cachedAssetPromise;

    @synchronized(self)
    {
        if (!cachedAssetPromise)
        {
            cachedAssetPromise = [PMKPromise new:^(PMKPromiseFulfiller fulfiller, PMKPromiseRejecter rejecter) {
                // Build request
                NSDictionary *oid = [SLObjectIdTransform serialize:self.nid];
                NSDictionary *query = @{@"criteria": @{@"attributes": oid}, @"limit": @1};
                // Send request
                [[SLStore sharedStore] find:[SLAsset class] withQuery:query]
                .then(^(NSArray *assets) {
                    NSLog(@"Assets: %@", assets);
                    if ([assets count] > 0)
                    {
                        return fulfiller([assets objectAtIndex:0]);
                    } else
                    {
                        return fulfiller(nil);
                    }
                })
                .catch(rejecter);
            }];
        }

        return cachedAssetPromise;
    }
}

Update: No it doesn't... singletons are for classes, not instances! -.-

Glavin001 commented 10 years ago

Trick was to remove the static and move the PMKPromise *cachedAssetPromise to the top like:

@implementation SLAttribute {
    PMKPromise *cachedAssetPromise;
}

This does work well and shows the different assets and caches the promise as expected :+1: .

See http://stackoverflow.com/a/13263345