Previous Entry Share Next Entry
Always use notification name globals, not literal strings!
latest
chanson
What's wrong with this code?
- (void)registerForNotificationsFromTask:(NSTask *)task ( {
    [[NSNotificationCenter defaultCenter]
        addObserver:self
           selector:@selector(taskDidTerminateNotification:)
               name:@"NSTaskDidTerminateNotification"
             object:task];
}
If you didn't notice anything wrong, look again.

What's bad about this is that it's passing a string literal instead of a global variable for the notification name. The code should really look like this:
- (void)registerForNotificationsFromTask:(NSTask *)task ( {
    [[NSNotificationCenter defaultCenter]
        addObserver:self
           selector:@selector(taskDidTerminateNotification:)
               name:NSTaskDidTerminateNotification
             object:task];
}
Isn't that better? (Among other things, Xcode will offer to complete the NSTaskDidTerminateNotification global variable for you — unlike the contents of a string literal.)

This is a bug that often results from copying & pasting from documentation into code. "I need this notification, it needs to be a string, so I'll just put @"" around it." The type of a notification name is, in fact, NSString but you don't have to pass a string literal for that. Instead, pass the global variable that exists for each notification name and you're guaranteed that the right thing will happen.

If you're creating and using your own notifications, be sure to follow the Cocoa pattern and create your own global variables containing the notification name. Otherwise you're at the mercy of typos within string literals.

Update: Sanjay Samani helpfully pointed out that by constant string I meant string literal. Thanks, Sanjay! I've updated my post with this correction. (Not sure where my memory was…)

  • 1

"Constant String"

(Anonymous)
In case this confuses C die hards, another phrase for "constant string" is "string literal" and I am so glad that someone told me about the dangers of string literals early in my career.

Of course avoiding them is not just good practice with Notifications, but throughout your programming. One exception I use myself is for accessing Key/Value pairs (e.g. -valueForKey:@"name") as I found it more readable with syntax colouring to use string literals. Though thinking about it, the correct solution would be to change the syntax colouring of global & project constants.

(Sanjay Samani, DayTime Software)

Underlying values != variable name

(Anonymous)
There are cases where the underlying value is not the same as the global variable name, NSPasteboard type's are a good example of this,and more subtle ones like NSNibOwner is @"NSOwner". It shouldn't matter, like you say, always use the global.

заклепка для одежды купить
брендовая детская одежда интернет магазин
r одежда
интернет магазин недорогой одежды украина
вешалки для одежды купить
футболки муж и жена
686 одежда купить
одежда селин би купить
одежда helly hansen купить
купить одежду через интернет костюм
кружка в марьино
футболка с совой
одежда акции
футболка на заказ москва
бейсболка diesel
reima детская одежда распродажа
майки в краснодаре
купить одежда богнер
магазин белой одежды
где можно купить рэперскую одежду
брендовая одежда и обувь купить
cropp town кепки
футболка сборной голландии
печать надписей на футболках
футболка фрак
архангельск магазины одежды
элитная детская одежда интернет магазин
футболка олимпиада
магазин одежды вайлдберриз
магазин одежды oliver
майка jack daniels
футболки с приколами для детей
купить нарядную одежду большой размер
купить одежду в кракове
прикольные футболки в питере
футболки гриффины
майки стрейч
интернет магазин одежды новосибирск
sum 41 футболки
работа в магазине одежды в спб
где в иваново купить футболку
stan футболки
футболка бэтмен купить
магазины одежды г москва
магазин одежды sela
одежда эмо
стиль 80 х в одежде
психоделические футболки
одежда для йоги
http://futbolka-ja-feja.co.tv/map.php

http://www.lovejerseys.com/nba-jersey-c-66.html/

(Anonymous)
Almost every young people have one or more Cheap basketball jerseys (http://www.lovejerseys.com/nba-jersey-c-66.html/). It is not only a way to show the pride for the favorite teams, but also comfortable when you are exercising. Cheap basketball jerseys (http://www.lovejerseys.com/nba-jersey-c-66.html/) are the best choice for wearing in summers. The authentic jerseys are so expensive that not any average football fan can afford. Then, you can get it online for bargain.

układy poker

(Anonymous)
[url=http://www.madzia636.inten.pl/index.php?m=3&wpis=126]darmowe kasyno[/url] ruletka bonus bez depozytu poker [url=http://www.nowa.lecznica.rzeszow.pl/e/Kasyno-gry,1072]kasyno online bez depozytu[/url] [url=http://www.poliglota.mieszkaniedlazaka.pl/e/Kasyno-internetowe,4216]automaty hazard[/url] gra online poker jak grać w bingo [url=http://85.128.158.153/908_katalog/index.php?a=szcz&id=29600]gry kasyno maszyny[/url] [url=http://gastronomia.frytownice.info/info-50444.html]darmowe kasyna[/url] hazard gra american poker [url=http://wibrator.na-blogu.pl/index.php/2010/10/20/zasady-panujace-w-kasynach/]ruletka kasyno[/url] [url=http://www.madzia871.inten.pl/index.php?m=3&wpis=176]kasyno gier[/url] gra bingo gra w poker [url=http://www.pozycjonowaniewarszawa.tk/e/Kasyno-online,3037]gry kasyno maszyny[/url] [url=http://wireboot.zxy.me/index.php?a=szcz&id=7568]gry darmowe kasyno[/url] maszyny kasyno bonus bez depozytu poker [url=http://www.katalog.pisma-procesowe.eu/index.php?inc=record&get=7-12431]kasyno online[/url]

Ab program Weight

(Anonymous)
You certainly deserve a round of applause for your post and more specifically, your blog in general. Very high quality material

  • 1
?

Log in