Real examples where NSProxy class is useful and why?

后端 未结 2 1528
抹茶落季
抹茶落季 2021-02-19 14:08

I have been wondering why is NSProxy class so important. Why does an object need to keep its instance variables inside other objects? I need examples to understand when to use i

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-19 14:31

    Example A: Imagine you'd be writing an object persistence layer (like CoreData, but much better of course ;) ).

    Let's say you can fulfill a query for thousands of items in your database really quick by just looking at the index-tree, without the cost of reading and initializing the complete item. You could use NSProxy to implement lazy-loading. Use your index table to locate the primary key of the object, but instead of creating that object, return an NSProxy that knows the primary key of the real object.

    Only when another database lookup is required, the proxy object creates the item and redirect all future messages to it. The calling code would only deal with the NSProxy item, and never now about the lazy-loading performed under the hood.

    Example B (this is OS X, sorry): NSOutlineView behaves really odd, when you have the same item in the outline hierarchy twice. Very common problem when you have a smart group feature in your app. The solution: use different proxies in the outline view, pointing to the same object.

提交回复
热议问题