`
13146489
  • 浏览: 252852 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

weak reference

阅读更多
资料
delegate:
http://en.wikipedia.org/wiki/Delegation_pattern
Objective-C 2.0
// A custom view that scrolls its children.
@interface TCScrollView : NSView {
 
   id delegate; // A delegate that wants to act on events in this view
}
 
-(IBAction)scrollToCenter:(id)sender; // A method that can be bound to a button in the UI
-(void)scrollToPoint:(NSPoint)to;
 
// Accessors. Implementation not shown.
@property (nonatomic, assign) id delegate;
 
@end
 
// This is a formal protocol: implementor doesn't have to implement all or even any of 
// the optional methods in the protocol
@protocol TCScrollViewDelegate 
 
@optional
-(BOOL)scrollView:(TCScrollView*)scrollView shouldScrollToPoint:(NSPoint)newPoint;
 
@end
 
@implementation TCScrollView
 
@synthesize delegate;
 
-(IBAction)scrollToCenter:(id)sender; { 
 
   [self scrollToPoint:NSPointMake(0,0)];
}
 
-(void)scrollToPoint:(NSPoint)to {
 
   BOOL shouldScroll = YES;
 
   // If we have a delegate, and that delegate indeed does implement our delegate method,
   if(delegate && [delegate respondsToSelector:@selector(scrollView:shouldScrollToPoint:)])
     shouldScroll = [delegate scrollView:self shouldScrollToPoint:to]; // ask it if it's okay to scroll to this point.
 
   // If not, ignore the scroll request.
   if(!shouldScroll) 
      return;  
 
   // Scrolling code omitted.
}
 
@end
 
@interface MyCoolAppController : NSObject <TCScrollViewDelegate> {
 
   IBOutlet TCScrollView* scrollView;
}
 
@end
 
@implementation MyCoolAppController
 
-(void)awakeFromNib {
 
  [scrollView setDelegate:self];
}
 
-(BOOL)scrollView:(TCScrollView*)scrollView shouldScrollToPoint:(NSPoint)newPoint {
 
  if(newPoint.x > 0 && newPoint.y > 0)
    return YES;
 
  return NO;
}
 
@end

http://stackoverflow.com/questions/4516165/java-command-pattern-vs-iphone-delegate-pattern
delegate:Cocoa Fundamentals Guide.pdf(p183)
Implementing a Delegate for a Custom Class
To implement a delegate for your custom class, complete the following steps:
■ Declare the delegate accessor methods in your class header file.
- (id)delegate;
- (void)setDelegate:(id)newDelegate;
■ Implement the accessor methods. In a memory-managed program, to avoid retain cycles, the setter
method should not retain or copy your delegate.
- (id)delegate {
return delegate;
}
- (void)setDelegate:(id)newDelegate {
delegate = newDelegate;
}
In a garbage-collected environment, where retain cycles are not a problem, you should not make the
delegate a weak reference (by using the __weak type modifier). For more on retain cycles, see “Object
Ownership and Disposal” in Memory Management Programming Guide. For more on weak references in
garbage collection, see “Garbage Collection for Cocoa Essentials”.
■ Declare a formal or informal protocol containing the programmatic interface for the delegate. Informal
protocols are categories on the NSObject class. If you declare a formal protocol for your delegate, make
sure you mark groups of optional methods with the @optional directive.
“The Form of Delegation Messages” (page 180) gives advice for naming your own delegation methods.
■ Before invoking a delegation method make sure the delegate implements it by sending it a
respondsToSelector: message.
- (void)someMethod {
if ( [delegate respondsToSelector:@selector(operationShouldProceed)] ) {
if ( [delegate operationShouldProceed] ) {
// do something appropriate
}
}
}
The precaution is necessary only for optional methods in a formal protocol or methods of an informal
protocol.
1、Memory Management Programming Guide.pdf(p18)
Weak References to Objects
Retaining an object creates a “strong” reference to that object. An object cannot be deallocated until all of
its strong references are released. An object’s lifetime is thereby determined by the owners of its strong
references. In some cases, this behavior may not be desired. You may want to have a reference to an object
without preventing the object from deallocating itself. For these cases, you can obtain a “weak” reference.
A weak reference is created by storing a pointer to an object without retaining the object.
Weak references are essential in cases where a circular reference would otherwise be set up. For example, if
Object A and Object B communicate with each other, each needs a reference to the other. If each retains the
other, neither object ever gets deallocated until the connection is broken, but the connection is not broken
until one of the objects is deallocated. Catch-22. To break the circle, one object takes a subordinate role and
obtains a weak reference to the other. As a concrete example, in a view hierarchy, a parent view owns, and
hence retains, its child views, but a child view does not own its parent; the child still needs to know who its
parent is, so it keeps a weak reference to its parent.
Additional cases of weak references in Cocoa include, but are not restricted to, table data sources, outline
view items, notification observers, and miscellaneous targets and delegates.
Important: In Cocoa, references to table data sources, outline view items, notification observers, and delegates
are all considered weak (for example, an NSTableView object does not retain its data source and the
NSApplication object does not retain its delegate). The documentation only describes exceptions to this
convention.

You need to be careful about sending messages to objects for which you only hold a weak reference. If you
send a message to an object after it has been deallocated, your application will crash. You must have
well-defined conditions for when the object is valid. In most cases, the weak-referenced object is aware of
the other object’s weak reference to it, as is the case for circular references, and is responsible for notifying
the other object when it deallocates. For example, when you register an object with a notification center,
the notification center stores a weak reference to the object and sends messages to it when the appropriate
notifications are posted. When the object is deallocated, you need to unregister it with the notification center
to prevent the notification center from sending any further messages to the object, which no longer exists.
Likewise, when a delegate object is deallocated, you need to remove the delegate link by sending a
setDelegate: message with a nil argument to the other object. These messages are normally sent from
the object’s dealloc method
2、@property assign

http://stackoverflow.com/questions/1072541/i-have-a-circular-reference-how-can-i-create-a-weak-reference-in-objective-c
http://stackoverflow.com/questions/793224/how-can-i-make-a-weak-reference-to-a-parent-object-when-using-properties
3、addsubviews 与 superview
- (void)addSubview:(UIView *)view
Parameters
view
The view to be added. This view is retained by the receiver. After being added, this view appears on top of any other subviews.
Discussion
This method retains view and sets its next responder to the receiver, which is its new superview.

Views can have only one superview. If view already has a superview and that view is not the receiver, this method removes the previous superview before making the receiver its new superview.
分享到:
评论

相关推荐

    Python Weak Reference Ext.-开源

    Python中的弱引用(Weak Reference)是一种特殊的数据结构,它允许程序员创建对对象的引用,但不增加对象的引用计数。这种机制在处理大型数据结构或者循环引用问题时尤其有用,因为它可以避免内存泄漏。在Python标准库...

    Java功底之Reference

    2. **弱引用(Weak Reference)**:弱引用比软引用更弱,一旦发现一个对象只有弱引用,无论内存是否充足,垃圾收集器都会在下次GC时回收该对象。这使得弱引用非常适合用于构建不阻塞垃圾收集的关联数据结构。 3. **...

    Java中的引用类型详解:强引用、软引用、弱引用与虚引用

    从JDK 1.2版本开始,Java引入了四种不同级别的引用:强引用(Strong Reference)、软引用(Soft Reference)、弱引用(Weak Reference)和虚引用(Phantom Reference)。这些引用类型提供了灵活的内存管理策略,允许...

    理解Java中的弱引用(Weak Reference)

    本篇文章尝试从What、Why、How这三个角度来探索Java中的弱引用,理解Java中弱引用的定义、基本使用场景和使用方法。由于个人水平有限,叙述中难免存在不准确或是不清晰的地方,希望大家可以指出,谢谢大家:) ...

    Java学习之Reference、Eclipse调优、jvisualvm使用

    通常,Java有四种类型的引用:强引用(Strong Reference)、软引用(Soft Reference)、弱引用(Weak Reference)和虚引用(Phantom Reference)。强引用是最常见的类型,当对象被强引用持有时,垃圾回收器不会回收...

    Objective C Pocket Reference.rar

    - **弱引用(Weak Reference)**:防止循环引用,避免内存泄漏。 - **强引用(Strong Reference)**:默认的引用类型,持有对象直到引用计数为零。 4. **Foundation框架** - **NSObject**:所有Objective-C对象...

    java面试经典100题

    Java 5引入了四种不同的引用类型,它们分别是强引用(Strong Reference)、软引用(Soft Reference)、弱引用(Weak Reference)和虚引用(Phantom Reference)。每种引用类型在内存管理和垃圾回收上有不同的特点: ...

    Java中的强软弱虚引用

    为了更好地理解和控制对象的生命周期,Java提供了四种不同类型的引用:强引用(Strong Reference)、软引用(Soft Reference)、弱引用(Weak Reference)以及虚引用(Phantom Reference)。每种引用都有其特定的...

    iOS 5 ARC完全指南

    ARC中还有“弱引用”(weak reference)的概念,弱引用不会增加对象的引用计数,因此不会阻止对象被释放。弱引用主要用于避免循环引用,比如在代理模式中,避免代理与被代理对象之间互相持有导致的内存泄漏。当一个...

    自动引用计数.playground.zip

    2. 弱引用(Weak Reference):弱引用不会增加对象的引用计数,且不阻止对象的销毁。当对象的强引用计数归零时,即使还有弱引用存在,对象也会被销毁。 3. 无主引用(Unowned Reference):无主引用类似于弱引用,但...

    Java引用类型编程开发技术共13页.pdf.zip

    7. 弱引用(Weak Reference):弱引用对象的存在不会阻止垃圾收集器的回收。一旦没有任何强引用或软引用指向对象,即使是弱引用,该对象也会被立即回收。 8. 虚引用(Phantom Reference):虚引用并不直接与对象相...

    Java中弱引用软引用虚引用及强引用的区别Java开发Ja

    3. **弱引用(Weak Reference)**: - 弱引用比软引用更弱,只要垃圾收集器运行,无论内存是否充足,都会回收弱引用指向的对象。弱引用常用于实现内存敏感的缓存。 - 示例:`WeakReference&lt;String&gt; weakRef = new ...

    Java中的软引用弱引用和虚引用.docx

    本文将深入探讨Java中三种特殊的引用类型——软引用(Soft Reference)、弱引用(Weak Reference)以及虚引用(Phantom Reference),并分析它们如何帮助我们更好地管理内存资源。 #### 二、基础知识回顾 在深入了解这三...

    ThreadLocal,你真的了解吗?

    3. 弱引用(Weak Reference): - 弱引用对象会在垃圾回收器扫描时立即回收,无论内存是否充足。 - 示例:`WeakReference sr = new WeakReference(new String("hello"));` - ThreadLocal 内部使用弱引用来管理...

    FindBugs规则整理_中文版.pdf

    1. LG_LOST_LOGGER_DUE_TO_WEAK_REFERENCE: Potential lost logger changes due to weak reference in OpenJDK。FindBugs发现OpenJDK中的一个潜在的不兼容问题,即logger配置改变时可能会丢失。解决方法是使用强引用...

    JVM 38 道面试题及答案.docx

    * 弱引用(Weak Reference):对象相比较软引用,要更加无用一些,它拥有更短的生命周期。 * 虚引用(Phantom Reference):一种形同虚设的引用,在现实场景中用的不是很多,它主要用来跟踪对象被垃圾回收的活动。 ...

    各个大厂--iOS开发精品面试题 题集大全.zip

    内存管理是iOS开发中的重要部分,面试官可能会询问ARC(Automatic Reference Counting)的工作原理、强引用循环(Strong Reference Cycle)及其解决方法,以及弱引用(Weak Reference)和无主引用(Unowned ...

Global site tag (gtag.js) - Google Analytics