Non-retaining array for delegates

后端 未结 10 1359
感动是毒
感动是毒 2020-11-29 18:41

In a Cocoa Touch project, I need a specific class to have not only a single delegate object, but many of them.

It looks like I should create an NSArray for these del

相关标签:
10条回答
  • 2020-11-29 19:22

    I found this bit of code awhile ago (can't remember who to attribute it to).

    It's quite ingenius, using a Category to allow the creation of a mutable array that does no retain/release by backing it with a CFArray with proper callbacks.

    @implementation NSMutableArray (WeakReferences)
        + (id)mutableArrayUsingWeakReferences {
        return [self mutableArrayUsingWeakReferencesWithCapacity:0];
        }
    
        + (id)mutableArrayUsingWeakReferencesWithCapacity:(NSUInteger)capacity {
        CFArrayCallBacks callbacks = {0, NULL, NULL, CFCopyDescription, CFEqual};
        // We create a weak reference array
        return (id)(CFArrayCreateMutable(0, capacity, &callbacks));
        }
    @end
    

    EDIT Found the original article: http://ofcodeandmen.poltras.com

    0 讨论(0)
  • 2020-11-29 19:27

    This one from NIMBUS would be more simple:

    NSMutableArray* NICreateNonRetainingMutableArray(void) {
      return (NSMutableArray *)CFArrayCreateMutable(nil, 0, nil);
    }
    
    NSMutableDictionary* NICreateNonRetainingMutableDictionary(void) {
      return (NSMutableDictionary *)CFDictionaryCreateMutable(nil, 0, nil, nil);
    }
    
    NSMutableSet* NICreateNonRetainingMutableSet(void) {
      return (NSMutableSet *)CFSetCreateMutable(nil, 0, nil);
    }
    
    0 讨论(0)
  • 2020-11-29 19:28

    Check documentation of NSValue valueWithNonretainedObject method :

    This method is useful for preventing an object from being retained when it’s added to a collection object (such as an instance of NSArray or NSDictionary).

    0 讨论(0)
  • 2020-11-29 19:28

    You do not want to do this! Cocoa Touch have several concepts for sending events, you should use the proper concept for each case.

    1. Target-action: For UI controls, such as button presses. One sender, zero or more receivers.
    2. Delegates: For one sender and one receiver only.
    3. Notification: For one sender, and zero or more receivers.
    4. KVO: More fine grained that notifications.

    What you should do is to look into how to use NSNotificationCenter class. This is the proper way to send a notification that have more than one receiver.

    0 讨论(0)
提交回复
热议问题