creating blocks for addObserverForName:object:queue:usingBlock: [closed] - ios

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
Can someone show me how to create block for this method that holds multiple parameters as I only know how to create blocks for a single parameter method.
addObserverForName:object:queue:usingBlock:

What I do is sending a single parameter that is actually an NSDictionary ... so I can send lot of information in a single parameter.
GL HF

The notification center method addObserverForName:object:queue:usingBlock: has a fixed block signature for the block that gets invoked. You can't add additional parameters to the block.
However, that isn't usually a problem. Blocks inherit the scope in which they are defined. If you pass a block to the notification center from an instance method of an object, all the instance variables and properties of the object that makes the call are available, as are local variables in the actual method that makes the addObserverForName:object:queue:usingBlock: call.
The system plays some games to make that happen. Local variables are copied from the stack to the heap at the time the block is passed.
Referring to "self" in a block is generally a bad idea however. That can cause the object (self) to be retained and create retain cycles. In that case I usually create a local variable "myself" that points to self and set it up at the beginning of the method.

Related

Is setting singleton to nil a good policy or it should never be set to nil? [iOS, Swift] [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I know we should completely avoid singleton, as its difficult to test them in unit testing.
Let assume someone has written a code for singleton and i have been assigned task to write unit tests for it.
Is setting singleton to nil a good policy or it should never be set to nil?
If setting to them is nil policy then,
should i make it an optional or should i crate a private setter and public getter, then later on write reset() function to make singleton nil ?
Why I want to set to nil to perform unit test on singleton class.
ok, i would like to extend this question. assuminng that its not good practise to set singleton nil. Another query in mind is, suppose someone has already written code for singleton class.
now they have assigned task to you to test that singleton class. (not the other class which uses them).
how to work on that ? as for SUT, we mostly alloc SUT in setup() method and set to nil in teardown() method.
but since it is singleton , we can not set to nil, and also in setup() me can't alloc it, we can refer to same object again and again.
First thing Singleton class should never be nil. As it's name says we are allocating memory for singleton class only once.
You Can't 'deinit' singleton class if you want to test you can do it like creating methods.
e.g if your singleton class is for like NotificationManager then create two methods subscribeForNotification() & unsubscribeForNotification() You can init or deinit object available in singleton class but not deinit singleton class.

Need help in iOS app's architecture. Use Singletons or not? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I have a class ServiceClass, a closure function in this class eg LoginViaEmail, calls APILayer. APILayer calls HttpLayer and JSONHandler and returns output to ServiceClass. ServiceClass further returns some info to ViewController when completionblock is received.
My questions are
Shall I make ServiceClass as Singleton? But then everybody says that they are anti-pattern and not a good approach.
If they are so bad, why does Apple use them? eg NSFileManager, NSWorkspace, UIApplication etc,
If not Singleton, then what shall I use? Make instance of ServiceClass every time I use it? Wouldn't that take too much memory?
Don't use a bunch of singletons if you want to write effective, independent and uncoupled, tests. If you don't care about tests, then singletons are fine.
Here's a half-way-house architecture that I use:
Have an overall App or Container class that owns all the services, and creates them, and injects them into each other as needed (so your services have all dependencies as properties, and don't access any statics)
Have your UIAppDelegate class own the single instance of the Container. This is the only 'singleton' in the app.
UIViewControllers etc get references to the Container, and its services through the UIAppDelegate, at viewDidLoad time, and save them into local properties. Eg they inject themselves. It would be nice to make this automatic.
Tests can set up and tear down the Container, or individual services as needed, knowing that other tests can't effect them.
If your ServiceClass doesn't need some sort of state inside, i would use class func inside and call it like that:
ServiceClass.fetchSomething { fetchedData in
self.updateUI(with: fetchedData)
}
You can use singleton class for this but if you do so then you should manage any network handler queue like functionality also.
Because network requests should be in asynchronous manner with concurrency support.
At any point of time in application, you may need to perform multiple request at once.
Using singleton pattern, this task will be little bit more complex and will need more management of multiple requests.
So if this is not an issue, then you can easily use singleton pattern.
Otherwise you can create a category of NSObject. This category will initiate the request send it to other request handling, parsing classes and then callBack response to sender.
Using category of NSObject, you will have benefit that you can initiate request from any class (as model, controller of any other helper class).
For example as I have used:
self.startPostRequest(withInput: payload,
requestApi: kApiScheduleList,
httpMethod: kHttpMethodPost,
headerDict: nil,
success: { (response) in
}, failure: { (error) in
})
Hope this will help.
If you need to discuss on any point, then let me know.

In the iOS API Reference, what does "receiver" mean? [duplicate]

This question already has an answer here:
In Apple's Documentation for NSObject, what is the idea of the "receiver"?
(1 answer)
Closed 6 years ago.
I've been able to make sense of and use the API Reference fairly consistently so far, but the one thing that really irks me is that every time I run into this term, I basically have to ignore the definition in which it's used and figure out how the method/property in question works by applying it in code.
So can anyone clarify this matter for me?
When the iOS API Reference mentions a "receiver" (and it does this a lot), what is that term referring to?
Example of such a method description:
https://developer.apple.com/reference/uikit/uiview/1622442-convert
Converts a point from the receiver’s coordinate system to that of the specified view.
The receiver is the object on which a method is being invoked. For example, in this code:
let myView = UIView()
myView.convert(point, to: otherView)
The receiver of the convert(_:to:) method is myView.
This terminology comes from SmallTalk and Objective-C, where methods are called "messages" that you "send" to objects, and your objects "receive" them.

Difference between self.view.addSubview and view.addSubview

I have done a bunch of coding in swift and prefer to do a lot programmatically and I was wondering what the difference was between these two:
self.view.addSubview(someNewView)
view.addSubview(someNewView)
they both seem to work. Is one better for some reason? Are they actually that different?
If this is a dumb question or already answered it can be removed. Just a thought.
There's no real difference, although you may see the use of self more often from previously Objective-C developers. From the docs:
In practice, you don’t need to write self in your code very often. If
you don’t explicitly write self, Swift assumes that you are referring
to a property or method of the current instance whenever you use a
known property or method name within a method.
...
The main exception to this rule occurs when a parameter name for an instance method has the same name as a property of that instance. In this situation, the parameter name takes precedence, and it becomes necessary to refer to the property in a more qualified way.
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Methods.html

Lazy Instantiation Disadvantages iOS [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
So it seems lazy instantiation is widely used and everybody know the advantages of lazy instantiation.
Which leads to the question: should we lazy instantiate every object?
Which I seriously doubt.
So the question is, what are the disadvantages of lazy instantiation?
Sample taken from (Apple Sample LocateMe):
- (NSDateFormatter *)dateFormatter {
if (dateFormatter == nil) {
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterLongStyle];
}
return dateFormatter;
}
This will give us the advantage of only initialising this object when it is needed.
By the way, the above sample taken from Apple, it seems like they only lazy instantiate "readonly" objects.
Ok, figured I'll reword my response in the form of an answer (ad you've got too many comments now)...
In the example you've given, it's safe to use the same object instance multiple times as its internal state is unaffected. That is, it's providing a service and won't keep state between calls.
As a general rule, lazy instantiation is only really relevant to Singletons or those instances provided through a factory. For instance, like in your example, instances living for the duration of a "service" or application - such as resource handling. Usually though, you often just want to create a new object instance when you need it.
The advantages/ disadvantages of lazy initialization are:
You need initialize an object only once and a single instance will suffice for all service calls. State won't be held between calls. The benefit here is that the object may be time-consuming to load and so you avoid start up cost or, in a singleton context, you avoid instantiating multiple expensive objects. This also applies to memory footprint - one instance, rather than many.
There is a cost at run-time though if you do lazily ini an object as you've essentially delayed its construction. So, at run-time, when a user is waiting, you go and create an expensive object. Not ideal so you should avoid this - if it's a long-service object again.
In the example you've given, there's also a question of responsibility for memory. The client code is clearly responsible for releasing this instance. If it's a long serving object, where do they do it? Well, you may have to watch the NSApp's delegate for applicationWillTerminate.
If an instance maintains state that would be set between invocations of methods on an instance then this pattern can't work. The state of the instance may be inconsistent (may have been changed) between calls.
Note also that this is an instance method setting the value of an instance var if it's null... This means that, in this case, you will still have one instance per your enclosing class instance (class where this method is defined). In this context, your enclosing instance is responsible for clean up. Really, I think that this is for clarity of code, rather than memory management. Or perhaps the enclosing class is long-lived and it saves re-creating your formatter (perhaps it's more expensive to recreate than reset).
will edit if anything else comes to mind. Hope it helps.

Resources