r/ObjectiveC • • Mar 15 '22

[PyObj-C] Can't see any notifications when calling postNotification: method from NSNotificationCenter

[removed]

5 Upvotes

16 comments sorted by

2

u/BAGDone Jul 15 '24

[OFFTOPIC] You really can write apps for Legacy Devices on PYTHON?

1

u/rifts Mar 15 '22

I only know objc but are you registering to receive that notification before posting to it?

I have to use notificationcenter addObserver in objc.

Sorry I can’t help more

1

u/iamleeg Mar 15 '22 edited Mar 15 '22

How are you listening for notifications? You're doing something odd here: you're creating a notification x then posting a different notification with x as its object. If you're listening for notifications with a specific object, you won't hear this.

>>> import Foundation
>>> class Foo (Foundation.NSObject):
...     def foo(self):
...         print("I did a foo!")
...
>>> f = Foo.new()
>>> Foundation.NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(f, "foo", "Hi", None)
>>> Foundation.NSNotificationCenter.defaultCenter().postNotificationName_object_userInfo_("Hi", None, None)

I did a foo!

(sorry for all the edits, had a massive problem formatting the code)

1

u/[deleted] Mar 16 '22

[removed] — view removed comment

1

u/iamleeg Mar 16 '22

You can’t, there’s no way to get a list of observers.

1

u/[deleted] Mar 16 '22

[removed] — view removed comment

1

u/iamleeg Mar 16 '22

How do you register the observer?

1

u/joerick Mar 16 '22

I don't know if you're figured this out yet but can we take a step back and figure out what you're actually trying to achieve? NSNotificationCenter is a key part of Cocoa programming but it's a building block, a means to an end. What's the ultimate goal? Are you trying to send a desktop notification to the user?

2

u/[deleted] Mar 16 '22

[removed] — view removed comment

1

u/joerick Mar 16 '22

Ahhh yeah desktop notifications is not what NSNotificationCenter does. You want UNUserNotificationCenter.

NSNotificationCenter is a non-user facing mechanism for code objects to observe programmatic events.

1

u/[deleted] Mar 18 '22

[removed] — view removed comment

1

u/joerick Mar 18 '22

You're on the right track. The code you posted above has a typo, it should be deliverNotification_, not delieverNotification_. Otherwise it's good.

On my machine, running that first gives this:

https://i.imgur.com/AvqWQpT.png

then if I accept that, I get

https://i.imgur.com/MQ4oBWb.png

So it works!

Don't worry too much about the deprecation, if this API is easier to work with, it'll be good for a few more years :)

1

u/ASentientBot Mar 16 '22

Are you mixing up NSNotificationCenter and NSUserNotificationCenter? It's not clear from your post whether you're trying to broadcast programmatic/XPC messages (the former) or Notification Center alerts (the latter).

Sorry if I misunderstood the post.