Re: Future of Cocoa #2

2019-12-12 Thread Charles Srstka via Cocoa-dev
> On Dec 10, 2019, at 5:57 PM, Turtle Creek Software via Cocoa-dev 
>  wrote:
> 
> Xojo is new to me, but it appears more a SwiftUI than a Cocoa substitute.

Xojo is just the new name for RealBASIC, which has been around forever.

It wouldn’t be my first choice.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Need for Swift

2019-10-16 Thread Charles Srstka via Cocoa-dev
> On Oct 16, 2019, at 2:38 PM, Jean-Daniel via Cocoa-dev 
>  wrote:
> 
>> Le 16 oct. 2019 à 11:49, Stephane Sudre via Cocoa-dev 
>> mailto:cocoa-dev@lists.apple.com>> a écrit :
>> 
>> On Tue, Oct 15, 2019 at 2:26 PM Sandor Szatmari via Cocoa-dev
>> mailto:cocoa-dev@lists.apple.com>> wrote:
>> 
>>> But honestly, I don’t have enough Swift experience to know if you can write 
>>> bad Swift code.
>> 
>> I'm just reading Swift code here and there and it's my personal
>> opinion that 75% of the Swift code I read is bad code.
> 
> That matches my observation whatever the language is. 
> This is not something related to Swift. This is just how most developers 
> works.

+1

>> Why do Swift developers think it's mandatory to write code that is illegible?
>> Is Swift mainly used by freelances or consultants that will not have
>> to maintain the software?
> 
> Not more than other projects with language designed to be easy to use and 
> usable by as many people as possible.
> 
> You won’t find as much bad C++ and Rust code because the complexity of the 
> languages filter out casual developers.

And it’s certainly not as if there’s not a lot of terrible Objective-C code out 
there.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Need for Swift

2019-10-15 Thread Charles Srstka via Cocoa-dev
> On Oct 14, 2019, at 10:44 PM, Laurent Daudelin via Cocoa-dev 
>  wrote:
> 
> Are people supposed to know instinctively when you unwrap with “?” and when 
> you do with “!”?

It’s quite simple; you nearly always unwrap with `?`.

The tiny minority of the time that `!` is needed is when you *know* something 
will never be nil, because a guarantee is being made somewhere else that the 
Swift compiler can’t see. Most of the time, in practice, this is because you’re 
dealing with data included with your own application. This plist key will 
*always* be set… because it’s in a plist that I included in the application, 
and I know what’s in it. This outlet will always be connected, because it’s in 
a nib that I included in the app, and I *know* that I’ve always connected it. 
If I forget to connect that outlet, it’s a *bug*, and the app *should* crash.

The other time `!` can be useful is when you’re not writing code that’s meant 
for production, when you’re prototyping or just screwing around in a playground 
or the debugger, and you don’t really care about correctness.

Seeing lots of `!` in production Swift is a code smell.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Need for Swift

2019-10-14 Thread Charles Srstka via Cocoa-dev
> On Oct 14, 2019, at 7:21 PM, Jens Alfke  wrote:
> 
>> On Oct 14, 2019, at 5:02 PM, Charles Srstka > <mailto:cocoa...@charlessoft.com>> wrote:
>> 
>> Swift, on the other hand, can actually *be* a scripting language if you want 
>> it to; put #!/usr/bin/env swift at the top of a source file, give it execute 
>> permissions, and voilà, it’ll run just like a script.
> 
> *Anything* can be a scripting language in that sense, in Unix. I could write 
> a two-line script called "run_c" containing*:
>   #! /bin/bash
>   cc "$1" -o /tmp/a.out && /tmp/a.out
> and put it somewhere in my path; then I can put "#! /usr/bin/env/run_c" at 
> the top of any C source file and run it as a script.
> 
> To me, "scripting language" strongly implies a CLI, plus dynamic typing, and 
> no boilerplate (so I can write one-line programs.)
> 
> —Jens
> 
> * Typed in Mail. Should work, but I haven't tested it.

Yeah, but Swift actually has first-party support for it, unlike that rather 
hacky solution. Its syntactical similarity to scripting languages was also a 
big part of the promotional materials that Swift launched with (see: 
https://www.apple.com/ne/newsroom/2015/12/03Apple-Releases-Swift-as-Open-Source/
 
<https://www.apple.com/ne/newsroom/2015/12/03Apple-Releases-Swift-as-Open-Source/>
 - "Introduced in 2014, Swift is the fastest growing programming language in 
history and combines the performance and efficiency of compiled languages with 
the simplicity and interactivity of popular scripting languages.”) It seems 
clear that the intention is to blur the lines a bit, although 
implementation-wise Swift is certainly very much on the compiled, static-typed 
side of the fence.*

Charles

* Unless, of course, you put `dynamic` on everything, on an Apple platform. 
Then, you’re basically writing Objective-C with a different syntax.

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Need for Swift

2019-10-14 Thread Charles Srstka via Cocoa-dev
> On Oct 14, 2019, at 2:30 PM, Jens Alfke  wrote:
> 
>> On Oct 14, 2019, at 11:25 AM, Carl Hoefs via Cocoa-dev 
>> mailto:cocoa-dev@lists.apple.com>> wrote:
>> 
>> I see Computer Science students here falling into two groups. The group that 
>> likes Swift generally likes scripting languages, Python, and the like.
> 
> Whoa, I completely disagree. Objective-C is much, much closer to scripting 
> languages than Swift, with all of its dynamic features:
> 
> * It has the 'id' type that represents any type of object
> * you can send a message to an arbitrary object whether or not its class 
> declares it
> * you can intercept unhandled messages and do arbitrary things to handle them
> * you can add, remove or override methods at runtime
> * you can even create classes at runtime
> 
> Swift is very strongly-typed and less dynamic: it's very strict and nit-picky 
> about types, protocol conformance, etc. Much more like C++.
> 
> Are you lumping Swift in with scripting languages simply because its 
> method-call syntax is more normal looking? Or because compiler type inference 
> sometimes allows you to omit variable types?

It’s kind of a funny dichotomy; Swift is a strictly typed language under the 
hood, but it *looks* like a scripting language on the surface, what with its 
type inference, JavaScript-looking-like “let” and “var” declarations, implicit 
closure parameters, and whatnot. Objective-C, on the other hand, is like one 
step down from Ruby on the dynamism scale under the hood, but on the surface it 
looks like a statically-typed language, thanks to the mandatory types on every 
variable declaration, even if the type is just ‘id’—although it usually isn’t, 
since in common practice we specify object types even though it’s not strictly 
necessary, and some of them can be kind of obnoxious (hello, block syntax).

Swift, on the other hand, can actually *be* a scripting language if you want it 
to; put #!/usr/bin/env swift at the top of a source file, give it execute 
permissions, and voilà, it’ll run just like a script.

>> (There is a third group that likes both languages, but it is very small.)
> 
> Most experienced iOS/Mac developers I know like both.


I’d agree with that.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Need for Swift

2019-10-12 Thread Charles Srstka via Cocoa-dev
> On Oct 12, 2019, at 11:24 AM, Charles Srstka  wrote:
> 
> The string nil checks, in particular,

This was meant to be “The strict nil checks.” Ah, the joy of mailing lists, 
where there’s no edit feature.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Need for Swift

2019-10-12 Thread Charles Srstka via Cocoa-dev
> On Oct 12, 2019, at 10:55 AM, Pier Bover via Cocoa-dev 
>  wrote:
> 
> Yeah I think Apple saw Obj-C as a barrier for developer adoption. I don't
> think that's too far from the truth considering the emphasis on teaching
> Swift to young devs, Playgrounds, the marketing about teenagers making
> their first app, etc.
> 
> Swift has its quirks but most people around me prefer it over Obj-C too,
> even experienced devs. From StackOverflow trends and other metrics as soon
> as Swift was announced the popularity of Obj-C declined steadily even when
> it was clear Swift was still not ready for production:
> 
>   - https://www.tiobe.com/tiobe-index/objective-c/ 
> 
>   - https://insights.stackoverflow.com/trends?tags=objective-c 
> 
Swift’s first few versions were awful, but the community has been very 
responsive in responding to developer feedback and what we have now is really 
quite a nice language, possibly the nicest I’ve used. The string nil checks, in 
particular, are something I’ve become a believer in, especially when spending a 
bunch of time trying to debug an issue while writing projects in other 
languages that turns out to be a nil showing up somewhere where we didn’t 
expect it.

The main quibble I have with it is the Objective-C bridge, which contains much 
more magic than I’d prefer, and of course certain legacy issues that come along 
with having to use the Objective-C frameworks (hello, autorelease pools). When 
writing cross-platform code on Linux or something, these complaints are of 
course moot. I hope they release a Windows version at some point; I’d really 
like to see Swift gain more acceptance as a general-purpose programming 
language.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Thoughts on Cocoa

2019-10-12 Thread Charles Srstka via Cocoa-dev
> On Oct 11, 2019, at 5:29 PM, tblenko--- via Cocoa-dev 
>  wrote:
> 
> Me, I still don’t understand why, given the long history of support at 
> Apple/NeXT for C++

…what?

> and the maturity of the compilers available, there is any need for Swift. But 
> there it is. Or, there they are. Perhaps this is the way the younger 
> generation overtthrows the older? Or not, but I’m pretty sure there is no 
> compelling business argument for it.


Holy hell, Swift isn’t perfect, but I’d rather use it over C++ a thousand times 
over.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Thoughts on Cocoa

2019-10-11 Thread Charles Srstka via Cocoa-dev
> On Oct 11, 2019, at 12:44 AM, Jens Alfke  wrote:
> 
> 
>> On Oct 10, 2019, at 6:18 PM, Richard Charles via Cocoa-dev 
>>  wrote:
>> 
>> Just a guess but perhaps management had an awakening when they found the 
>> time and effort expended to write the next even better version of Finder in 
>> Carbon was substantially more difficult and costly that the prior Cocoa 
>> version.
> 
> The only Cocoa—>Carbon Finder transition I know of was before 10.0 shipped. 
> The development versions had a NeXT file manager with a Mac UI skin, but 
> before release that was replaced with a Carbon-ized port of (a subset of) the 
> MacOS 9 Finder. That Finder lived on for a few years before being replaced by 
> a new rewritten Cocoa version.
> 
> —Jens

The NeXT/Rhapsody file manager was what I was referring to.

As for the 10.0 Finder, I’m sure it shared code with the OS 9 finder, but it 
was an essentially new app based on PowerPlant (which the OS 9 Finder, to the 
best of my knowledge, was not). It did not feel much like the OS 9 Finder, and 
it was missing a lot of basic functionality that the OS 9 Finder had had, much 
of which was gradually reintroduced over the years. The Cocoa rewrite of the 
Finder did not appear until Snow Leopard was released in 2009. Notably, the 
Finder was still Carbon when Apple suddenly out of nowhere (again, from the 
perspective of an outsider) dropped the previously promised 64-bit Carbon 
support in 2007.

As for the Dock, there was no OS 9 analogue to that at all, so the only 
conclusion can be that it was rewritten in Carbon from the ground up, when a 
Cocoa one had been previously available. This is difficult to explain other 
than as a statement of confidence in Carbon.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Thoughts on Cocoa

2019-10-10 Thread Charles Srstka via Cocoa-dev
> On Oct 4, 2019, at 4:51 AM, Jeremy Hughes via Cocoa-dev 
>  wrote:
> 
> Hi Jens,
> 
>> On 3 Oct 2019, at 20:04, Jens Alfke via Cocoa-dev > > wrote:
>> 
>> The people I hear complaining about this are those who, like you, didn't 
>> move to Cocoa. Carbon was a _temporary_ transition API*. 
> 
> It wasn’t clear to us (outside Apple) that Carbon was a temporary API until 
> 2007, when Apple suddenly abandoned 64-bit Carbon.

Yes, they marketed Carbon as a first-class citizen, promoted as “the basis for 
all life,” and even rewrote the Finder and Dock—which already had Cocoa 
implementations from NeXT—in Carbon just to prove that they were serious about 
it.

That last detail made a lot of people nervous about *Cocoa’s* future. There was 
a real possibility that it could have gone the way of OpenDoc or GX and joined 
the large graveyard of supposedly superior Apple technologies, whereas Carbon 
was the only framework being used by all the big clients that Apple couldn’t 
survive without, and for those first few years, it seemed to get a lot more 
development attention (Cocoa didn’t even support proper drag and drop until 
Jaguar).

I still remember reading this thread, and feeling nervous about it:

https://lists.apple.com/archives/cocoa-dev//2002/Jan/msg01366.html

The common assumption among the more level-headed at the time was that Cocoa 
was going to be gradually rewritten to sit on top of Carbon, with Carbon 
sticking around as the lower-level, closer-to-the-metal API. They actually did 
partially do this—for example, I think that the menu system is still Carbon 
under the hood.

In retrospect, it seems clear that the real issue driving things was that Apple 
in 2001 did not have the clout that they had in 2007. Apple was in a rather 
precarious position at the time, and was in no position to dictate terms to its 
large vendors like Adobe and Microsoft on whom it depended for its survival. If 
we had known the success that Apple would subsequently reach, we might have 
been able to predict that Carbon would eventually be phased out, but to those 
living in the moment, there was no guarantee that that would happen, or even 
that Apple would still be around after all this time (indeed, if the 
inevitability of this *had* been obvious, I would have loaded up on stock). 
Hindsight is easy.

None of that makes it surprising that Carbon is gone in 2019, though (sadly, as 
I’m going to miss a lot of the game library that’s being wiped out by this).

Charles
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Carbon -> Cocoa

2018-08-19 Thread Charles Srstka
> On Aug 18, 2018, at 2:45 PM, Mike Crawford  wrote:
> 
> "older OS versions", porting to 10.6 or later vs. 10.10 or later:
> 
> I at first intended all the drivers I write for my clients to work on
> Snow Leopard 10.6, but after actually attempting to do so I settled
> upon supporting El Capitan 10.11, sometimes just Sierra 12.6.
> 
> There are some occasional but quite serious problems with new APIs
> appearing during a minor release so you can't just set your Deployment
> Target to a major release's first drop.  To get drivers to build - and
> I expect Cocoa code as well - one must take _great_ care to check
> Apple's doc for most if not all of your API calls to determine when
> they first appeared.
> 
> For one particular client's USB function driver we actually had three
> kernel extensions.  I at first planned to package this in just one
> kext bundle but because of time pressure shipped them as three
> separate ones.
> 
> Two of the drivers had Deployment Targets of 10.12, the third 10.11.
> I had some manner of good reason for doing it this way, but I've just
> been up all night nosediving deeply into Wikipedia and all manner of
> Epic Talk Page Flame Wars so just now I'm too thrashed to actually
> remember what it was.


Recent version of Xcode make this much easier to deal with, though, thanks to 
the @available attribute (#available in Swift). If you have your warnings set 
up correctly, this will result in a warning when you use an unavailable API 
outside of an @available block. In Swift, it’s a compiler error rather than a 
warning, so you’re basically forced to do this.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Data, enumerateBytes: separate blocks?

2017-12-25 Thread Charles Srstka
> On Dec 25, 2017, at 12:23 PM, Daryle Walker  wrote:
> 
> Not quite.
> 
> My first versions of this idea, pre-Swift and therefore using NSData with 
> Objective-C, did use the direct search functions that come with the NSData 
> API. There seems to be a detail you missed in my sample code that explains 
> the use of “enumerateBytes”:
> 
> LF-only is also a searched-for separator.
> 
> That means no matter what, I must find the first CR and the first LF. Then I 
> compare their relative positions (and check for another CR if the spacing is 
> right). What happens if whichever byte value is second is gigabytes away from 
> the first? (Or equivalently, only one value is present and there’s gigabytes 
> of trailing data to fail to find the other value.) I would end up wasting the 
> user’s time for a second result I’d never use.

With either Collection or Data, the value that index(of:) returns for 
the second value will be one greater than what it returns for the first value 
in that case, regardless of how the data is stored under the hood.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Data, enumerateBytes: separate blocks?

2017-12-24 Thread Charles Srstka
> On Dec 24, 2017, at 2:51 PM, Quincey Morris 
> <quinceymor...@rivergatesoftware.com> wrote:
> 
> On Dec 24, 2017, at 04:45 , Charles Srstka <cocoa...@charlessoft.com 
> <mailto:cocoa...@charlessoft.com>> wrote:
>> 
>> you could consider making its interface take generic collections of UInt8
> 
> This would not solve the *general* problem Daryle raised. He’s looking for a 
> way to test the logic of some buffer-boundary-crossing code, which makes 
> sense only if he has multiple buffers, which means he must be using 
> “enumerateBytes”, which not supported by Collection. If he doesn’t use 
> enumerateBytes, then he doesn’t need anything but Data anyway.
> 
> However, considering what appears to be the *actual* problem (finding the 
> first CR or CR-LF or CR-CR-LF separator in a byte sequence), he could use 
> Data without using enumerateBytes, and still not risk copying the data to a 
> contiguous buffer.
> 
> This solution would use Data’s “index(of:)” to find the first CR, then a 
> combination of advancing the index and subscripting to test for LF in the 
> following 1 or 2 positions.

That’s basically what I was thinking (well, using Collection’s 
index(of:) rather than just Data’s). However, if enumerateBytes legitimately 
does need to be used, you could also create a protocol containing that method 
and make Data and DispatchData both retroactively conform to it.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Data, enumerateBytes: separate blocks?

2017-12-24 Thread Charles Srstka
> On Dec 24, 2017, at 1:03 AM, Daryle Walker  wrote:
> 
>> On Dec 22, 2017, at 2:18 PM, Quincey Morris 
>> > > wrote:
>> 
>> On Dec 22, 2017, at 08:48 , Daryle Walker >  >> 
>> wrote:
>>> 
>>> DispatchData would need to be convertible to Data.  Is there a way to do 
>>> the conversion in Swift?
>> 
>> Actually, on consideration, I think not. It would be if DispatchData was 
>> bridgeable like Data, but it isn’t, and I don’t see any way of extracting 
>> its underlying reference. This leaves you with two options that I can see:
>> 
>> 1. Use an Obj-C helper function, taking an array of input buffers, and 
>> returning a dispatch_data_t object that combines them, cast to a NSData*. 
>> You can then use the returned reference as Data.
>> 
>> 2. Move your Data extension to DispatchData. That’s what I was asking about 
>> earlier — is there any reason why you couldn’t just use DispatchData rather 
>> than Data, in all the code that deals with this data set? In that case, you 
>> can just build the DispatchData in Swift.
>> 
>> IAC, you should probably submit a bug report. Since dispatch_data_t is 
>> documented to be a subclass of NSData, there should probably be a mechanism 
>> for getting Data and DispatchData values as equivalents of each other, 
>> without any unprovoked copying of the underlying data.
> 
> This code is not for private use within an app, but for something I plan to 
> publicize as a library on GitHub. So the interface has to stay as using Data. 
> (Fortunately, this part of the interface, an extension to Data, is private.) 
> DispatchData and Data don’t even have a custom shared interface (just the 
> general RandomAccessCollection) I could use here to not repeat myself in 
> implementation.

Depending on what your library does, you could consider making its interface 
take generic collections of UInt8. Then, your APIs would accept Data, 
DispatchData, [UInt8], ContiguousArray, etc.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Creating NSTableView programmatically

2017-12-20 Thread Charles Srstka
> On Dec 20, 2017, at 4:23 AM, Quincey Morris 
>  wrote:
> 
>> The original code used all the same three array controllers, with the exact 
>> same subclassing of the target's one.
> 
> This is where I take the fifth. 
> 
> When bindings were introduced, back in 10.3 or 10.4, then refined in 10.5, it 
> looked very much like Apple was trying to sell a sort of data-manipulation 
> “language” constructed out of bindings and NS…Controller classes. While this 
> worked great for pushing glue code out of .m source files and into .nib files 
> (this predated .xib files), it’s was too general, too inscrutable and too 
> clumsy to have much wider appeal. In effect, the whole thing with bindings 
> died at 10.5, except for the part where they were used within IB to hook up 
> specific controls to specific properties. That part is really all we use 
> today.

That’s going a little far, isn’t it? I still find bindings/KVO useful for a lot 
of cases where I want to keep things synced. For example, in Pacifist I have a 
main outline view, and a search results table on the side (currently in a 
drawer, although that’s changing in the currently-under-development Swift 
rewrite). The selected item in the search results and in the main outline view 
should always be the same, and I do that by setting things up, via a system of 
computed properties and keyPathsForValuesAffecting methods, so that the 
table’s selectionIndexes and the outline’s selectionIndexPaths are both 
essentially backed by the same underlying property. The result is that not only 
does it update the selection in the outline view when you change the selection 
in the search results, as you’d expect, but it also manages to update the 
selection in the *search results* if you select an item in the main outline 
view that happens to also be a search result. A big deal? No, but it’s one of 
those little details that makes an old Mac geek like me smile. ;-) I doubt I 
would have gone to the trouble of making it do that if I’d had to write the 
glue code manually.

Charles
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Creating NSTableView programmatically

2017-12-11 Thread Charles Srstka
> On Dec 11, 2017, at 4:59 AM, Eric Matecki  wrote:
> 
> 
> Hello,
> 
> I'm trying to implement in Objective-C on macOS *programmatically* the "Real 
> World Example" at the bottom of this page :
> https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CocoaBindings/Concepts/WhatAreBindings.html
>  
> 
> 
> …
> 
> -- 
> Keep intel OUTSIDE my Mac !
> Hiii !!! I can see Intel chips creeping around my G5 !

I dunno, to me it seems that trying to get NSTableView to work right without 
just using a nib is as much of a losing battle as still trying to fight the 
PPC->Intel transition in 2017… ;-)

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Is "-init" really needed?

2017-08-10 Thread Charles Srstka
> On Aug 10, 2017, at 9:44 AM, Alastair Houghton <alast...@alastairs-place.net> 
> wrote:
> 
> On 10 Aug 2017, at 15:24, Jeremy Hughes <moon.rab...@virginmedia.com 
> <mailto:moon.rab...@virginmedia.com>> wrote:
>> 
>>> On 10 Aug 2017, at 15:15, Alastair Houghton <alast...@alastairs-place.net 
>>> <mailto:alast...@alastairs-place.net>> wrote:
>>> 
>>> On 10 Aug 2017, at 15:09, Charles Srstka <cocoa...@charlessoft.com 
>>> <mailto:cocoa...@charlessoft.com>> wrote:
>>>> 
>>>> They’re equivalent syntactically, but performance-wise, +array and friends 
>>>> will cause the object to be put into an autorelease pool. Therefore, +new 
>>>> is better for performance.
>>> 
>>> Not with ARC they don’t.  The ARC logic circumvents the autorelease pool in 
>>> that case.
>> 
>> Are you sure?
> 
> Yes, I’m sure.  At the call site, ARC causes the compiler to emit a call to 
> objc_retainAutoreleasedReturnValue() or 
> objc_unsafeClaimAutoreleasedReturnValue(), while in the method itself, ARC 
> will use objc_autoreleaseReturnValue() or 
> objc_retainAutoreleaseReturnValue().  The latter looks at the code for the 
> call site and, assuming it matches, it will *not* do the autorelease and will 
> set a flag that causes objc_retainAutoreleasedReturnValue() to eliminate the 
> retain.

The frameworks (and thus, the implementation of +array) are not built using 
ARC. The -autorelease method is called manually, and the object is put in the 
autorelease pool. You can see this for yourself by making a small test app that 
calls [NSMutableArray array] and running it in Instruments, where the 
autorelease will be clearly visible.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Is "-init" really needed?

2017-08-10 Thread Charles Srstka
>  On Aug 10, 2017, at 8:59 AM, Alastair Houghton 
>  wrote:
> 
> On 10 Aug 2017, at 14:57, gerti-cocoa...@bitart.com 
>  wrote:
>> 
>> On Aug 10, 2017, at 02:18, Alastair Houghton  
>> wrote:
>>> 
>>> Personally I *would* still discourage +new in favour of class-specific 
>>> convenience constructors because I think it’s less expressive and also less 
>>> consistent (e.g. +array is better, in my opinion, than +new, not least 
>>> because +arrayWithObjects: and others exist).
>> 
>> [NSArray new] := [[NSArray alloc]init]
>> 
>> [NSArray array] := [[[NSArray alloc]init]autorelease]
>> 
>> +array and friends came along with the introduction of autorelease pools, to 
>> replace +new with something that didn't imply ownership (the oft mentioned 
>> special meaning of "new" as prefix). So while with ARC they are essentially 
>> equivalent, previously they were not.
> 
> Yes, I know that, thanks.
> 
> The point is, with ARC, they’re equivalent, and most new code uses ARC, so, 
> again, I’d discourage +new in favour of class-specific convenience 
> constructors.
> 
> Kind regards,
> 
> Alastair.

They’re equivalent syntactically, but performance-wise, +array and friends will 
cause the object to be put into an autorelease pool. Therefore, +new is better 
for performance.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Best practice with NSProgressIndicator

2017-07-28 Thread Charles Srstka
If you’re using Swift, I made a custom replacement for NSProgress that is 
specifically designed to cut down on CPU time used to update the progress. It 
allows you to set the granularity for notifications, so that they’ll only 
update when the progress has changed since the last update by an interval of 
your choosing.

You can check it out here if you like:

https://github.com/CharlesJS/CSProgress 


Charles

> On Jul 28, 2017, at 10:57 AM, Mark Allan  wrote:
> 
> Hi all,
> 
> I'm wondering if anyone has any thoughts about or links to best practices 
> when using determinate NSProgressIndicators.
> 
> I have an app with a helper tool that performs some lengthy process in a loop 
> and reports progress to the user.  It works out how many iterations of the 
> loop will be needed, sets the progressbar.maxValue, and then increments the 
> progress bar's value on each iteration.
> 
> The consumes a large amount of CPU time just for updating the progress bar, 
> so I'd like to cut down how often I update it.
> 
> Setting the max value to 100 and only updating 100 times (i.e. as a 
> percentage) seems too infrequent because the loop can iterate more than a 
> million times.
> 
> I'm debating doing it with an NSTimer firing every second, but wondered if 
> anyone had any other suggestions?
> 
> What are people's thoughts?
> 
> I've tried searching online and the only problems/solutions I can see are all 
> related to people's progress bars not updating properly because they're 
> blocking the main thread etc. I can't see anything related to best practice.
> 
> Many thanks
> Mark
> 
> PS. It could be that this is a case of premature optimisation...but I don't 
> think so!
> ___
> 
> Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)
> 
> Please do not post admin requests or moderator comments to the list.
> Contact the moderators at cocoa-dev-admins(at)lists.apple.com
> 
> Help/Unsubscribe/Update your Subscription:
> https://lists.apple.com/mailman/options/cocoa-dev/cocoadev%40charlessoft.com
> 
> This email sent to cocoa...@charlessoft.com

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Relative URLs, and string encodings

2017-07-24 Thread Charles Srstka
> On Jun 1, 2017, at 9:44 AM, Jonathan Taylor  
> wrote:
> 
> Can anyone help me with the seemingly simple task of creating a relative 
> NSURL for a filesystem object? The catch here (sorry!) is that I really do 
> need backward compatibility to 10.7, which rules out 
> fileURLWithFileSystemRepresentation:isDirectory:relativeToURL: (which I 
> suspect is the “right” way of doing this).
> 
> My attempt like:
> [NSURL URLWithString:[path 
> stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding] 
> relativeToURL:relativeTo];
> 
> This had been working ok for some time, but I have just found it to be broken 
> for filenames containing unusual characters. In particular, it fails when 
> given a filename containing a “smart quote” (not easily created directly with 
> the keyboard, but auto-generated as part of a time machine backup, based on 
> the machine name).
> 
> Although I do not recall why I used 
> stringByAddingPercentEscapesUsingEncoding, I think it must have been because 
> it failed on some other filename pattern if I did not do that.
> 
> String encodings is something I know basically nothing about, I am afraid. I 
> am speculating that what is happening is that the fancy apostrophe is not 
> ASCII and so my code does not work for that filename. I can change the 
> encoding to NSUnicodeStringEncoding, and things seem ok, but I don’t know 
> whether that will now definitely work for all filenames, or whether I have 
> just stored up an even more obscure problem for the future.
> 
> So, finally getting to two actual questions:
> 1. Will unicode encoding give me a robust solution here?
> 2. Is there a differnet, better way (pre-10.9) I should be using to create a 
> relative URL?
> 
> Thanks for any advice
> Jonny.

I’d construct a path using -[NSFileManager 
stringWithFileSystemRepresentation:length:], then make a URL from that using 
+[NSURL fileURLWithPath:].

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Who owns a child view controller?

2017-07-14 Thread Charles Srstka
> On Jul 14, 2017, at 10:09 AM, Jeremy Hughes  
> wrote:
> 
>> On 14 Jul 2017, at 14:40, Steve Christensen > > wrote:
>> 
>> On Jul 14, 2017, at 3:50 AM, Jeremy Hughes > > wrote:
>>> 
>>> I’m still not entirely clear on when autorelease pools are used in Swift. 
>>> There is a WWDC video which says that they’re used in code that interfaces 
>>> with Objective-C, but Greg Parker’s comments in this thread indicate that 
>>> autorelease is also used behind the scenes in native Swift code - except 
>>> that in many cases the compiler is able to optimise it out of existence. 
>>> Apple’s Swift book doesn’t mention autorelease.
>> 
>> I think the hazard here is that you are trying to build a mental model of 
>> when to expect autorelease pools (or autorelease behavior in general) and 
>> when not to. Worse, that you might design your code to fit those 
>> expectations.
> 
> Apple’s documentation states that there are times that you do want to 
> consider the memory effects of autorelease pools (and suggests adding your 
> own pools to prevent large accumulations of dead objects during loops) - so 
> knowing when they are used isn’t irrelevant.
> 
> Also, ARC is described as “deterministic” - which I’m possibly 
> misinterpreting as meaning "behaves in a predictable way".
> 
> Jeremy

I’d interpret it as “behaves in a consistent way.” Predictable is subjective, 
especially when autorelease pools are involved.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Who owns a child view controller?

2017-07-14 Thread Charles Srstka
> On Jul 14, 2017, at 8:51 AM, Alex Zavatone  wrote:
> 
> 
>> On Jul 14, 2017, at 5:50 AM, Jeremy Hughes  
>> wrote:
>> 
>>> On 12 Jul 2017, at 17:41, Jens Alfke  wrote:
>>> 
 On Jul 12, 2017, at 9:34 AM, Jeremy Hughes  
 wrote:
 
 // Prints "Why is childReference not nil?”
>>> 
>>> There may still be a reference in the autorelease pool. Check 
>>> childReference again ‘later’, i.e. on the next user event or after a 
>>> timer/delayed-perform.
>> 
>> Jens is correct. Here’s a modified version of the playground code that adds 
>> an autorelease pool:
> 
> In the interest of getting more of a clue in regards to these items, is it 
> possible to examine the autorelease pools?
> 
> Alex Zavatone

No, autorelease pools have always been maddeningly opaque. You can examine a 
particular object in Instruments though, to see when it’s been autoreleased.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Question about structs and enum placement in a project

2017-07-13 Thread Charles Srstka
Folders are good. I’d avoid glomming too many types into one file, because 
you’ll spend a lot of time scrolling through that file looking for things. 
Better to break things into smaller files where possible.

Charles

> On Jul 13, 2017, at 8:53 AM, Eric E. Dolecki <edole...@gmail.com> wrote:
> 
> Perhaps. Then maybe a folder of categorized structs and enums? I personally 
> dislike seeing them sprinkled throughout AppDelegate & other classes. It's 
> easy to cntrl-click to where they are defined, but it seems like a lot of 
> clutter.
> 
> On Thu, Jul 13, 2017 at 9:52 AM Charles Srstka <cocoa...@charlessoft.com 
> <mailto:cocoa...@charlessoft.com>> wrote:
> For a project of any appreciable size, that’s gonna be one huge file…
> 
> Charles
> 
> > On Jul 13, 2017, at 8:37 AM, Eric E. Dolecki <edole...@gmail.com 
> > <mailto:edole...@gmail.com>> wrote:
> >
> > I am planning on putting all my structs and enums into it's own swift file
> > - to keep my project cleaner. Seems safe enough, thoughts on this?
> >
> > Thanks,
> > Eric
> > ___
> >
> > Cocoa-dev mailing list (Cocoa-dev@lists.apple.com 
> > <mailto:Cocoa-dev@lists.apple.com>)
> >
> > Please do not post admin requests or moderator comments to the list.
> > Contact the moderators at cocoa-dev-admins(at)lists.apple.com 
> > <http://lists.apple.com/>
> >
> > Help/Unsubscribe/Update your Subscription:
> > https://lists.apple.com/mailman/options/cocoa-dev/cocoadev%40charlessoft.com
> >  
> > <https://lists.apple.com/mailman/options/cocoa-dev/cocoadev%40charlessoft.com>
> >
> > This email sent to cocoa...@charlessoft.com 
> > <mailto:cocoa...@charlessoft.com>
> 

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Question about structs and enum placement in a project

2017-07-13 Thread Charles Srstka
For a project of any appreciable size, that’s gonna be one huge file…

Charles

> On Jul 13, 2017, at 8:37 AM, Eric E. Dolecki  wrote:
> 
> I am planning on putting all my structs and enums into it's own swift file
> - to keep my project cleaner. Seems safe enough, thoughts on this?
> 
> Thanks,
> Eric
> ___
> 
> Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)
> 
> Please do not post admin requests or moderator comments to the list.
> Contact the moderators at cocoa-dev-admins(at)lists.apple.com
> 
> Help/Unsubscribe/Update your Subscription:
> https://lists.apple.com/mailman/options/cocoa-dev/cocoadev%40charlessoft.com
> 
> This email sent to cocoa...@charlessoft.com

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Who owns a child view controller?

2017-07-13 Thread Charles Srstka
> On Jul 12, 2017, at 6:30 PM, Quincey Morris 
>  wrote:
> 
> On Jul 12, 2017, at 16:19 , Greg Parker  > wrote:
>> 
>> "Unowned" means something else in Swift.
> 
> I suppose. I guess I’ve internalized “unowned” to mean “unretained but 
> crashes tidily” in Swift, but “unretained and crashes as messily as possible” 
> in Obj-C. :) Plus, Swift has “unowned(unsafe)” which means the same thing as 
> “unretained unsafe” in Obj-C.
> 
> (And, yes, I know that Swift “unowned” isn’t precisely unretained. Whoever 
> thought of this trick should get a round of applause.)
> 
> But you drove to me to look at the NSWindow documentation, and it appears 
> that the “delegate” property is (now) weak, not unsafe unretained. I’m not 
> sure when this changed.


It’s in the 10.13 release notes, so whether it’s actually changed yet is up to 
interpretation. ;-)

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Who owns a child view controller?

2017-07-12 Thread Charles Srstka
> On Jul 12, 2017, at 1:24 PM, Jens Alfke <j...@mooseyard.com> wrote:
> 
>> On Jul 12, 2017, at 10:38 AM, Charles Srstka <cocoa...@charlessoft.com 
>> <mailto:cocoa...@charlessoft.com>> wrote:
>> 
>> While that’s true, the main reason, as I understand it, that ARC doesn’t 
>> know enough about the object’s lifetime is that non-ARC code may be calling 
>> the method. In an all-ARC world, a method could always just return objects 
>> with a +1 retain count, and the consumer could just assume that and always 
>> balance the retain.
> 
> It could, but that results in _enormous_ numbers of retain/release calls. (I 
> speak from some experience, having once worked on performance optimization of 
> a project that did ref-counting this way.)
> 
> It’s generally cheaper overall to use autorelease, and that was one of the 
> reasons NeXT invented it* (besides the obvious benefit of simplifying MRR 
> code.)
> 
> —Jens
> 
> * I’m not actually sure they did; there’s an earlier technique called 
> “deferred reference counting” that might be equivalent.

How do you figure? Objects start with a +1 retain count, so returning that 
object with a +1 requires no retain/release calls at all; just return the 
thing. The client, in an all-ARC world, can then just assume the thing is +1 
and use it without needing to retain.

Objective-C ARC actually attempts to approximate this by peeking up the stack 
to see if the caller is ARC, in which case it skips the whole 
retain/autorelease dance and returns the object as is. But this is apparently 
not foolproof, since I often see autorelease calls showing up in Instruments in 
ARC apps, and even when it does work, the lookup process is still going to be 
more expensive than just returning the object.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Who owns a child view controller?

2017-07-12 Thread Charles Srstka
> On Jul 12, 2017, at 12:23 PM, Jens Alfke  wrote:
> 
> 
>> On Jul 12, 2017, at 9:54 AM, Jeremy Hughes  
>> wrote:
>> 
>> I’d forgotten about autorelease pools - but I guess they’re still there in 
>> Cocoa for backwards compatibility with pre-ARC code.
> 
> Autorelease is still necessary with ARC. There are cases where ARC doesn’t 
> know enough about object lifetimes at compile-time, and has to e.g. 
> autorelease a temporary object before returning it from a method.

While that’s true, the main reason, as I understand it, that ARC doesn’t know 
enough about the object’s lifetime is that non-ARC code may be calling the 
method. In an all-ARC world, a method could always just return objects with a 
+1 retain count, and the consumer could just assume that and always balance the 
retain.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Is cloning the same as copying in APFS?

2017-06-27 Thread Charles Srstka
> On Jun 27, 2017, at 4:45 PM, Rick Mann <rm...@latencyzero.com> wrote:
> 
>> 
>> On Jun 27, 2017, at 14:30 , Charles Srstka <cocoa...@charlessoft.com 
>> <mailto:cocoa...@charlessoft.com>> wrote:
>> 
>>> On Jun 27, 2017, at 4:17 PM, Rick Mann <rm...@latencyzero.com 
>>> <mailto:rm...@latencyzero.com>> wrote:
>>> 
>>> Thanks for that, Charles!
>>> 
>>> I wasn't sure because of the existence of the clonefile() call in 
>>> , implying that operation was different from copyfile(), 
>>> but looking more closely at the sample code, I see that you can call 
>>> copyfile() with COPYFILE_CLONE, which seems like it will clone if possible 
>>> and copy if not.
>>> 
>>> But there didn't seem to be equivalent calls in NSFileManager, hence my 
>>> question.
>> 
>> Apple clearly wants the clone feature to get used. :-) The ability to do a 
>> copy the old way is still there if you drop down to C, but since I can’t 
>> think of too many reasons to want to do that, it makes sense to leave it out 
>> of the high-level API.
> 
> Agreed. Thanks for the code, and for showing the other techniques. In my 
> case, I still have to support HFS+, and I want to do that with hard links. I 
> wish there was an API to clone-or-hardlink, but I can do that.

That should be easy enough to do. One thing I’d recommend would be checking the 
volumeSupportsFileCloningKey key on URLResourceValues, rather than checking the 
file system type itself. That way, if APFS gets supplanted by some even better 
file system in the future, you’ll already support it.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Is cloning the same as copying in APFS?

2017-06-27 Thread Charles Srstka
> On Jun 27, 2017, at 4:17 PM, Rick Mann  wrote:
> 
> Thanks for that, Charles!
> 
> I wasn't sure because of the existence of the clonefile() call in 
> , implying that operation was different from copyfile(), but 
> looking more closely at the sample code, I see that you can call copyfile() 
> with COPYFILE_CLONE, which seems like it will clone if possible and copy if 
> not.
> 
> But there didn't seem to be equivalent calls in NSFileManager, hence my 
> question.

Apple clearly wants the clone feature to get used. :-) The ability to do a copy 
the old way is still there if you drop down to C, but since I can’t think of 
too many reasons to want to do that, it makes sense to leave it out of the 
high-level API.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Is cloning the same as copying in APFS?

2017-06-27 Thread Charles Srstka
> On Jun 27, 2017, at 12:28 AM, Jens Alfke  wrote:
> 
>> On Jun 26, 2017, at 7:38 PM, Rick Mann > > wrote:
>> 
>> But there's actually a POSIX "clone" API, and so I wonder if a copy is 
>> different from a clone.
> 
> The low level file copying API that I’m aware of is , which is 
> Apple specific. It has options for doing copy-on-write.
> I don’t know if NSFileManager’s copy method clones files. I would assume that 
> it does, on APFS.

Well, I mean, you could always *try* it ;-)

import Foundation

func unclonedSize(of url: URL) throws -> off_t {
var list = attrlist(bitmapcount: UInt16(ATTR_BIT_MAP_COUNT),
reserved: 0,
commonattr: 0,
volattr: 0,
dirattr: 0,
fileattr: 0,
forkattr: attrgroup_t(ATTR_CMNEXT_PRIVATESIZE))

let bufsize = 4 + MemoryLayout.size
let buf = UnsafeMutablePointer.allocate(capacity: bufsize)
defer { buf.deallocate(capacity: bufsize) }

let err = url.withUnsafeFileSystemRepresentation { getattrlist($0, 
, buf, bufsize, UInt32(FSOPT_ATTR_CMN_EXTENDED)) }

if err != 0 { throw POSIXError.Code(rawValue: errno).map { 
POSIXError($0) } ?? CocoaError(.fileReadUnknown) }

let attrsize = buf.withMemoryRebound(to: UInt32.self, capacity: 1) { 
$0.pointee }

if attrsize < bufsize { throw CocoaError(.fileReadUnknown) }

var unclonedSize: off_t = 0

_ = withUnsafeMutableBytes(of: ) { memcpy($0.baseAddress!, 
buf + 4, MemoryLayout.size) }

return unclonedSize
}

do {
let sourceURL = URL(fileURLWithPath: "/tmp/tempfile1")
let destURL = URL(fileURLWithPath: "/tmp/tempfile2")

let sortaRandomData = Data(bytes: (0..<100 * 1024).map { 
UInt8(extendingOrTruncating: $0) })

try sortaRandomData.write(to: sourceURL)

print("Uncloned size of source file: \(try unclonedSize(of: 
sourceURL))")

try FileManager.default.copyItem(at: sourceURL, to: destURL)

print("Uncloned size of dest file: \(try unclonedSize(of: destURL))")
} catch {
print("Error occurred: \(error.localizedDescription)")
}

- - - - - - - - -

outputs:

Uncloned size of source file: 102400
Uncloned size of dest file: 0

So, it seems quite clear that (NS)FileManager does, in fact, clone the files 
you tell it to copy. :-)

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Converting a Storyboard into separate NIBs.

2017-06-19 Thread Charles Srstka
> On Jun 19, 2017, at 4:29 PM, Alex Zavatone  wrote:
> 
> From line 153 of UIViewController.h: 
> 
>   As a convenience, the default init method will do this for you,
>   and specify nil for both of this methods arguments.) In the specified NIB, 
> the File's Owner proxy should
>   have its class set to your view controller subclass, with the view outlet 
> connected to the main view. If you
>   invoke this method with a nil nib name, then this class' -loadView method 
> will attempt to load a NIB whose
>   name is the same as your view controller's class.
> 
> The pearl is here:
> 
> If you
>   invoke this method with a nil nib name, then this class' -loadView method 
> will attempt to load a NIB whose
>   name is the same as your view controller's class.

The documentation begs to differ, though:

https://developer.apple.com/documentation/appkit/nsviewcontroller/1434405-loadview

> Prior to OS X v10.10, the loadView() method did not provide well-defined 
> behavior if the nibName property’s value was nil. In macOS 10.10 and later, 
> however, you get correct behavior without specifying a nib name as long as 
> the nib file’s name is the same as that of the view controller. For example, 
> if you have a view controller subclass called MyViewController and a nib file 
> with the same name, you can employ the convenient initialization pattern 
> [[MyViewController alloc] init].

The AppKit release notes agree:

https://developer.apple.com/library/content/releasenotes/AppKit/RN-AppKitOlderNotes/index.html#10_10ViewController

> loadView: would previously not have well defined behavior if there was a 
> "nil" nibName. On 10.10 and later, if nibName is nil NSViewController will 
> automatically try to load a nib with the same name as the classname. This 
> allows a convenience of doing [[MyViewController alloc] init] (which has a 
> nil nibName) and having it automatically load a nib with the name 
> "MyViewController”.

The sense I get from these methods is that it might have kinda, sorta, 
accidentally worked in the past, but it shouldn’t be relied on.

Reading through those release notes reminded me of *another* caveat I’d 
forgotten; the functionality only correctly parses Swift class names in *10.11* 
and higher. Otherwise, it’ll be looking for MyProjectName.Foo.xib instead of 
Foo.xib like it should. So, if you’re using Swift, better to restrict usage of 
this feature to El Cap or better.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Converting a Storyboard into separate NIBs.

2017-06-19 Thread Charles Srstka
> On Jun 19, 2017, at 2:51 PM, Alex Zavatone  wrote:
> 
> What is EXCELLENT is when you take the storyboard and remove all the top 
> level views.  Then, create individual XIBs for each scene.  The 
> viewController.h specifies that “if a view can not be found, an .xib with the 
> same name of the class file will be looked for and will be loaded if found.”  
> I’ve seen this text in the viewController.h since 2009, if I recall 
> correctly, so it’s not due to change any time soon.

Keep in mind that according to the documentation, this is only true of macOS 
10.10 and higher. So if you are targeting 10.9 or below, you cannot do this 
(although it’s fairly trivial to write one’s own general NSViewController 
subclass that does this, as I did for many years before the built-in 
functionality was introduced).

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Release mode bindings crash and release pools

2017-06-17 Thread Charles Srstka
> On Jun 17, 2017, at 3:11 PM, Jonathan Mitchell <li...@mugginsoft.com> wrote:
> 
>> On 17 Jun 2017, at 16:36, Charles Srstka <cocoa...@charlessoft.com 
>> <mailto:cocoa...@charlessoft.com>> wrote:
>> 
>>> On Jun 17, 2017, at 8:36 AM, Jonathan Mitchell <li...@mugginsoft.com 
>>> <mailto:li...@mugginsoft.com>> wrote:
>> 
>> 
>> Just tested it on 10.9; it works :-)
>> 
>> import Foundation
>> 
>> class C: NSObject {
>>@objc dynamic var foo = "Foo"
>> }
>> 
>> let c = C()
>> 
>> let observer = c.observe(\.foo) { obj, _ in
>>print("Foo changed: now it's \(obj.foo)")
>> }
>> 
>> c.foo = "Bar"
>> 
>> Running it on my Mavs VirtualBox VM, this outputs:
>> 
>> $ ./kvotest
>> Foo changed: now it's Bar
>> 
>> Charles
> 
> Thanks for taking the time to test that.
> I haven’t had time this week to take look at the new 10.13 APIs.
> 
> Will the above translate to Obj-C?

It’s in the Swift overlay, so no Obj-C, sorry.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Release mode bindings crash and release pools

2017-06-17 Thread Charles Srstka
> On Jun 17, 2017, at 8:36 AM, Jonathan Mitchell <li...@mugginsoft.com> wrote:
> 
>> On 17 Jun 2017, at 14:21, Charles Srstka <cocoa...@charlessoft.com 
>> <mailto:cocoa...@charlessoft.com>> wrote:
>> 
>>> On Jun 17, 2017, at 5:32 AM, Jonathan Mitchell <li...@mugginsoft.com 
>>> <mailto:li...@mugginsoft.com> <mailto:li...@mugginsoft.com 
>>> <mailto:li...@mugginsoft.com>>> wrote:
>>> 
>>>> On 16 Jun 2017, at 23:18, Quincey Morris 
>>>> <quinceymor...@rivergatesoftware.com 
>>>> <mailto:quinceymor...@rivergatesoftware.com><mailto:quinceymor...@rivergatesoftware.com
>>>>  <mailto:quinceymor...@rivergatesoftware.com>>> wrote:
>>>> 
>>>> On Jun 16, 2017, at 14:41 , Jonathan Mitchell <li...@mugginsoft.com 
>>>> <mailto:li...@mugginsoft.com> <mailto:li...@mugginsoft.com 
>>>> <mailto:li...@mugginsoft.com>>> wrote:
>>>>> 
>>>>> I sometimes use the default NSObject bind: to set up a simple one way 
>>>>> operation as you describe as opposed to a discrete observation.
>>>> 
>>>> With macOS 10.13, the new block/closure-based KVO “addObserver” method is 
>>>> probably an easier way, although you do have to remove it manually.
>>>> 
>>> The block/closure improvements are long overdue IMHO.
>>> 
>>> I use a home brewed approach using BPBlockValueTransformer : 
>>> NSValueTransformer with bindings that gives a lot more flexibility.
>>> A trivial example involving a closure would be:
>>> 
>>>   BPBlockValueTransformer *blockValueTransformer = [BPBlockValueTransformer 
>>> valueTransformerWithBlock:^id(NSNumber *value) {
>>>  strongify(self);
>>>  return ([value boolValue] || self.isFree)? @“Freedom for all" : 
>>> @“Freedom for no-one";
>>>   }];
>>>   [self.titleTextField bind:NSValueBinding toObject:self.repObjCon 
>>> withKeyPath:@"selection.isHidden" options:@{NSValueTransformerBindingOption 
>>> : blockValueTransformer}];
>>> 
>>> The downside is that you cannot establish the binding in the NIB.
>> 
>> It’s definitely overdue; I’ve been using a blocks-based wrapper around KVO 
>> for years. 
> Is that a publicly available wrapper?

No, sorry; I probably should have released it, but it's just something I’ve 
been keeping around for internal use. If it’s any consolation, it’s pretty much 
obsolete now thanks to the new built-in observation support. ;-)

It did have one nice feature that the built-in functionality doesn’t have, 
which was a method to catch exactly one change in a certain key path, and after 
that change occurred, it would automatically tear itself down. This was pretty 
handy for adding “completion handler” support to objects that only let you know 
they were finished by setting an observable “done” property. Maybe if I decide 
that feature’s still relevant, I’ll port it to the new Swift key path 
functionality, I dunno.

>> A couple of notes, though, re-reading the message this replied to. The new 
>> blocks-based API, ‘observe()’, is actually part of the Swift overlay, which 
>> means it works on older macOS versions, not just 10.13. Also, you don’t have 
>> to remove it manually, and that’s in fact one of its major features—it 
>> automatically deregisters itself whenever the observer falls out of scope. 
>> So as long as you make sure you don’t set up a retain cycle with captured 
>> values, you can just stash the observer in an ivar, and when your object 
>> gets deallocated, your observer will be unregistered. Much easier than what 
>> we had to do before.
> It would be good if I could get this to work all the way back to 10.9 (that’s 
> my deployment target).
> 
> Accurately managing observation and object lifetimes is such a big time sink 
> that any improvement is always welcome.

Just tested it on 10.9; it works :-)

import Foundation

class C: NSObject {
@objc dynamic var foo = "Foo"
}

let c = C()

let observer = c.observe(\.foo) { obj, _ in
print("Foo changed: now it's \(obj.foo)")
}

c.foo = "Bar"

Running it on my Mavs VirtualBox VM, this outputs:

$ ./kvotest
Foo changed: now it's Bar

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Release mode bindings crash and release pools

2017-06-17 Thread Charles Srstka
> On Jun 17, 2017, at 5:32 AM, Jonathan Mitchell  wrote:
> 
>> On 16 Jun 2017, at 23:18, Quincey Morris 
>> > > wrote:
>> 
>> On Jun 16, 2017, at 14:41 , Jonathan Mitchell > > wrote:
>>> 
>>> I sometimes use the default NSObject bind: to set up a simple one way 
>>> operation as you describe as opposed to a discrete observation.
>> 
>> With macOS 10.13, the new block/closure-based KVO “addObserver” method is 
>> probably an easier way, although you do have to remove it manually.
>> 
> The block/closure improvements are long overdue IMHO.
> 
> I use a home brewed approach using BPBlockValueTransformer : 
> NSValueTransformer with bindings that gives a lot more flexibility.
> A trivial example involving a closure would be:
> 
>BPBlockValueTransformer *blockValueTransformer = [BPBlockValueTransformer 
> valueTransformerWithBlock:^id(NSNumber *value) {
>   strongify(self);
>   return ([value boolValue] || self.isFree)? @“Freedom for all" : 
> @“Freedom for no-one";
>}];
>[self.titleTextField bind:NSValueBinding toObject:self.repObjCon 
> withKeyPath:@"selection.isHidden" options:@{NSValueTransformerBindingOption : 
> blockValueTransformer}];
> 
> The downside is that you cannot establish the binding in the NIB.

It’s definitely overdue; I’ve been using a blocks-based wrapper around KVO for 
years. 

A couple of notes, though, re-reading the message this replied to. The new 
blocks-based API, ‘observe()’, is actually part of the Swift overlay, which 
means it works on older macOS versions, not just 10.13. Also, you don’t have to 
remove it manually, and that’s in fact one of its major features—it 
automatically deregisters itself whenever the observer falls out of scope. So 
as long as you make sure you don’t set up a retain cycle with captured values, 
you can just stash the observer in an ivar, and when your object gets 
deallocated, your observer will be unregistered. Much easier than what we had 
to do before.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Release mode bindings crash and release pools

2017-06-16 Thread Charles Srstka
> On Jun 16, 2017, at 4:32 PM, Quincey Morris 
> <quinceymor...@rivergatesoftware.com> wrote:
> 
> On Jun 16, 2017, at 13:48 , Charles Srstka <cocoa...@charlessoft.com 
> <mailto:cocoa...@charlessoft.com>> wrote:
>> 
>> This is incorrect.
> 
> It’s incorrect as a 2-way binding, but it works as a pair of so-called 1-way 
> bindings, with the proviso that they may need to be unbound manually, to 
> prevent reference cycles, which it sounds like is what Jerry is doing.
> 
> The thing that I always said that no one believed is that there’s really no 
> such thing as 1-way binding, and NSObject’s default implementation of the 
> “bind:…” method does *not* establish a binding. It’s *part* of the 
> implementation of a proper 2-way binding (as explained in the documentation 
> you referenced), and for a given receiver class the method only establishes a 
> 2-way binding if it’s an override that provides the rest of the functionality.
> 
> But every time I said that (until I stopped saying it about 10 years ago), 
> people would jump in and say that the NSObject implementation really does 
> establish a binding, and if it’s only one-way, that’s 
> just-fine-with-them-thank-you-very-much.
> 
> Thanks for the mention of mmalc, BTW. Them were the times. 

The thing is, though… I can’t find the thread anymore, but I distinctly 
remember posting some code that used -[bind:::] two ways like that, and getting 
chewed out for it. :-P The thing is, NSObject’s implementation of bind is meant 
to be part of a two-way bindings mechanism to be fully implemented by a view 
object, and it’s not really meant to be called outside of that context—and on 
top of that, it’s preferred that bindings go either through an 
NSObjectController, an NSViewController, or something else that implements 
NSEditorRegistration. Just using using -bind twice both ways between two 
arbitrary objects may accidentally work, but it’s not as intended. If all you 
want to do is synchronize some properties on two distinct objects, you’re 
supposed to use plain old KVO for that (as you mention, the new closure-based 
API in Swift is quite nice for doing this). And I did manage to find a quote 
for that last bit, by none other than mmalc himself: 
https://lists.apple.com/archives/Cocoa-dev/2004//Feb/msg01228.html 
<https://lists.apple.com/archives/Cocoa-dev/2004//Feb/msg01228.html>

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Release mode bindings crash and release pools

2017-06-16 Thread Charles Srstka
> On Jun 16, 2017, at 3:48 PM, Charles Srstka <cocoa...@charlessoft.com> wrote:
> 
>> On Jun 16, 2017, at 3:27 PM, Jerome Krinock <je...@ieee.org> wrote:
>> 
>>> On 2017 Jun 16, at 10:35, Quincey Morris 
>>> <quinceymor...@rivergatesoftware.com 
>>> <mailto:quinceymor...@rivergatesoftware.com>> wrote:
>>> 
>>> it takes additional custom code (like in the joystick example) to implement 
>>> the other direction. At least, that’s what I’ve been saying for years, 
>>> though I don’t think I’ve ever found a developer who believes me.
>> 
>> I believe you.  I think it was on your advice I've done this:
>> 
>> foo.bind("xxx", to: bar, ... );
>> bar.bind("yyy", to: foo, ... );
>> 
>> It works, but only in both directions with both statements.
> 
> This is incorrect. The recommended way to implement a two-way binding is to 
> override .bind(…) on the target object and set up KVO observations there. See 
> this page in the docs:
> 
> https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CocoaBindings/Concepts/HowDoBindingsWork.html
>  
> <https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CocoaBindings/Concepts/HowDoBindingsWork.html>
> 
> Charles

For more information (and a ton of sample code), see mmalc’s old page on the 
subject. Sadly, it fell off the Web when MobileMe shut down, but archive.org 
<http://archive.org/> still seems to have most of the info, including the 
project .zip files:

http://web.archive.org/web/20120620180050/http://homepage.mac.com:80/mmalc/CocoaExamples/controllers.html
 
<http://web.archive.org/web/20120620180050/http://homepage.mac.com:80/mmalc/CocoaExamples/controllers.html>

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Release mode bindings crash and release pools

2017-06-16 Thread Charles Srstka
> On Jun 16, 2017, at 3:27 PM, Jerome Krinock  wrote:
> 
>> On 2017 Jun 16, at 10:35, Quincey Morris 
>> > > wrote:
>> 
>> it takes additional custom code (like in the joystick example) to implement 
>> the other direction. At least, that’s what I’ve been saying for years, 
>> though I don’t think I’ve ever found a developer who believes me.
> 
> I believe you.  I think it was on your advice I've done this:
> 
> foo.bind("xxx", to: bar, ... );
> bar.bind("yyy", to: foo, ... );
> 
> It works, but only in both directions with both statements.

This is incorrect. The recommended way to implement a two-way binding is to 
override .bind(…) on the target object and set up KVO observations there. See 
this page in the docs:

https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CocoaBindings/Concepts/HowDoBindingsWork.html
 


Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: Property in class mirrored to user defaults

2017-06-12 Thread Charles Srstka
> On Jun 12, 2017, at 4:04 AM, Jonathan Taylor  
> wrote:
> 
> Hi all,
> 
> This feels like a very basic question, but one that I have not had any luck 
> searching for (maybe I am using the wrong terms?).
> 
> At the moment I have properties in a (singleton) class that are bound to UI 
> elements. At the moment they have the same automatic values every time the 
> app is launched, although the user can change them while it is running. What 
> I would like is for the user's previous choice to be remembered when the app 
> is next launched. Obviously this would seem to be a job for NSUserDefaults. I 
> am not sure quite what the right way to structure things is, though.
> 
> All the simple examples I have seen bind to NSUserDefaults and then if the 
> program actually wants to know what the value is, it simply accesses the 
> values directly on NSUserDefaults. I would prefer not to do that, though (see 
> below).
> 
> What I ~think~ I would like is to still be able to access the values as 
> properties of my class. That seems to me like the natural way, and it would 
> seem odd to have two categories of value, some accessed through properties on 
> the class, and some accessed some other way via NSUserDefaults. However, if I 
> bind the UI elements to the shared user defaults object, is that not what 
> will happen? Or is there some way that I can "link" my class and the user 
> defaults object, so that the properties are saved in user defaults but I can 
> still access them in a fairly seamless way from my class? I do like the idea 
> of having the properties (and their types) explicitly declared as part of my 
> class, rather than being mysterious objects that only exist in the user 
> defaults.
> 
> Does anyone have any advice on how I can achieve this, or on how I should be 
> thinking about all this differently?
> Thanks
> Jonny

If performance isn’t an issue, as it usually isn’t for properties linked to UI 
elements, and you don’t want to bind the UI elements directly to an 
NSUserDefaultsController, you can just use UserDefaults as the backing for a 
property, like this:

class MyClass: NSObject {   
// this is a property only so we can make key paths that will go 
through it
@objc private let userDefaults: UserDefaults
private static let fooDefaultsKey = "Foo"

@objc private static let keyPathsForValuesAffectingFoo: Set = 
["\(#keyPath(userDefaults)).\(MyClass.fooDefaultsKey)"]
@objc dynamic var foo: String {
get { return UserDefaults.standard.string(forKey: 
MyClass.fooDefaultsKey) ?? "" }
set { UserDefaults.standard.set(newValue, forKey: 
MyClass.fooDefaultsKey) }
}

override init() {
self.userDefaults = UserDefaults.standard

super.init()
}
}

This is pretty cool; on recent releases of macOS, it’ll respond to changes in 
the defaults even if they come from outside the process. So, if you observe the 
“foo” property, and then manually use /usr/bin/defaults to change the defaults, 
your notifications in the app will fire.

Alternately, you can just set up the property at init time and then update the 
defaults whenever it changes, like this. You won’t get the cool observation 
behavior, though, unless you use KVO’s infamously ugly observation APIs (the 
slick new closure-based one won’t work here, since we’re stuck with using 
string keys for this).

class MyClass: NSObject {   
private static let fooDefaultsKey = "Foo"

@objc dynamic var foo: String {
didSet { UserDefaults.standard.set(self.foo, forKey: 
MyClass.fooDefaultsKey) }
}

override init() {
self.foo = UserDefaults.standard.string(forKey: 
MyClass.fooDefaultsKey) ?? ""

super.init()
}
}

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: switching text field between editable and non-editable

2017-05-31 Thread Charles Srstka
> On May 31, 2017, at 2:18 PM, J.E. Schotsman <jesc...@xs4all.nl> wrote:
> 
>> On 31 May 2017, at 20:59, Charles Srstka <cocoa...@charlessoft.com 
>> <mailto:cocoa...@charlessoft.com>> wrote:
>> 
>> Does setting its needsDisplay property to true have any effect?
>> 
>> Charles
> 
> No. I’ve also tried 
> 
> myTextField.superview!.setNeedsDisplay( myTextField.frame ) 
> 
> in order to get the background redrawn but again I keep seeing the white text 
> background.

Try setting isBordered and isBezeled to false as well and you should probably 
get a clear background.

Note that this won’t work if the insertion point is in the text field, because 
when that’s the case, you’re actually seeing the field editor, not the text 
field, and the field editor will still have the white background. So you 
probably want to end editding first. If you’re using bindings to populate the 
field, this is easy; just send commitEditing() to the NSObjectController or 
NSViewController that the text field is bound to. Otherwise, you’ll have to do 
it the old-fashioned way with NSWindow.makeFirstResponder(_:) (or 
NSWindow.endEditing(for:) if that won’t work for whatever reason).

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: switching text field between editable and non-editable

2017-05-31 Thread Charles Srstka
> On May 31, 2017, at 1:51 PM, J.E. Schotsman  wrote:
> 
> Hello,
> 
> I have a hard time achieving what the message title says.
> Depending on user settings I want a text field to be either editable or 
> non-editable.
> 
> I’ve tried this:
> 
> if makeEditable
>   {   myTextField.isEditable = false
>   myTextField.drawsBackground = false }
> else
>   {   myTextField.isEditable = true
>   myTextField.drawsBackground = true }
> 
> Setting the editable property has the desired effect, but setting 
> drawsBackground has no effect.

Does setting its needsDisplay property to true have any effect?

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: Question about the Main Thread

2017-04-25 Thread Charles Srstka
> On Apr 25, 2017, at 4:37 PM, Charles Srstka <cocoa...@charlessoft.com> wrote:
> 
>> On Apr 25, 2017, at 9:51 AM, Dave <d...@looktowindward.com> wrote:
>> 
>> Mac Project.
>> 
>> Hi All, 
>> 
>> I’m using performSelector: withObject: afterDelay: in order to postpone 
>> further processing until after the current method/run loop as expired, this 
>> puts the request at the End of the Queue, my question is, is there anyway of 
>> putting it at the head of the Queue so it gets processing before other 
>> requests?
>> 
>> All the Best
>> Dave
> 
> Consider using NSOperationQueue (OperationQueue if you’re using Swift) 
> instead of performSelector:withObject:afterDelay:, and have a look at the 
> queuePriority property on Operation/NSOperation. The following code:
> 
>> import Foundation
>> 
>> let op1 = BlockOperation {
>>  print("op1")
>> }
>> 
>> let op2 = BlockOperation {
>>  print("op2")
>> }
>> 
>> let quitOp = BlockOperation {
>>  exit(0)
>> }
>> 
>> quitOp.addDependency(op1)
>> quitOp.addDependency(op2)
>> 
>> op1.queuePriority = .veryLow
>> op2.queuePriority = .veryHigh
>> 
>> OperationQueue.main.addOperations([op1, op2, quitOp], waitUntilFinished: 
>> false)
>> 
>> RunLoop.main.run()
> 
> outputs:
> 
>> op2
>> op1
> 
> This shouldn’t be taken as a guarantee, but it does make it more likely that 
> your operation will be executed before others.
> 
> Charles

Addendum:

After doing some further tests, it appears that the queuePriority property only 
affects the ordering relative to other (NS)Operations, and not other things 
done by CF/NSRunLoop. I guess I’d had some sort of idealistic vision of the 
main run loop submitting its operations to the main operation queue and having 
everything work in harmony. In fact, it’s quite the opposite; all operations on 
the main queue are performed *after* operations scheduled via CFRunLoop or the 
medieval performSelector:etc:etc: methods, so using (NS)OperationQueue will 
actually do the opposite of what you want.

From a quick look at the disassembly for __CFRunLoopRun, it appears that 
CFRunLoop executes things in the following order: observers, blocks, sources 
(performSelector:etc:etc: is implemented using a CFRunLoop source), and 
finally, operations on the main dispatch and operation queues. So, unless you 
want to kludge together a fake observer and then trigger it, which I would not 
recommend, your best bet is probably to use CFRunLoopPerformBlock. 
Unfortunately, there’s no way that I can see to prioritize things submitted 
this way, so you’ll still run in series with any other operations submitted via 
CFRunLoopPerformBlock, but you should run ahead of most everything else. The 
test below bears this out:

> import Foundation
> 
> let group = DispatchGroup()
> 
> class Foo: NSObject {
> @objc func bar() {
> print("something called via performSelector")
> group.leave()
> }
> }
> 
> // Do this stuff in an operation after the run loop starts, because it seems 
> if the operations are
> // added before the run loop is running, the first one enqueued will run 
> first no matter what.
> OperationQueue.main.addOperation {
> let op = BlockOperation {
> print("something called via the main operation queue")
> group.leave()
> }
> 
> op.queuePriority = .veryHigh
> 
> group.enter()
> OperationQueue.main.addOperation(op)
> 
> group.enter()
> DispatchQueue.main.async {
> print("something called via the main dispatch queue")
> group.leave()
> }
> 
> group.enter()
> Foo().performSelector(onMainThread: #selector(Foo.bar), with: nil, 
> waitUntilDone: false)
> 
> let cfRunLoop = RunLoop.main.getCFRunLoop()
> 
> group.enter()
> CFRunLoopPerformBlock(cfRunLoop, CFRunLoopMode.commonModes.rawValue) {
> print("Our thingy got called!")
> group.leave()
> }
> 
> CFRunLoopWakeUp(cfRunLoop)
> 
> group.notify(queue: DispatchQueue.main) {
> exit(0)
> }
> }
> 
> RunLoop.main.run()

outputs:

> Our thingy got called!
> something called via performSelector
> something called via the main dispatch queue
> something called via the main operation queue

Unfortunately, I don’t think this is documented anywhere, so there’s no 
guarantee it won’t change in future versions of macOS, but for now, it works.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: Question about the Main Thread

2017-04-25 Thread Charles Srstka
> On Apr 25, 2017, at 9:51 AM, Dave  wrote:
> 
> Mac Project.
> 
> Hi All, 
> 
> I’m using performSelector: withObject: afterDelay: in order to postpone 
> further processing until after the current method/run loop as expired, this 
> puts the request at the End of the Queue, my question is, is there anyway of 
> putting it at the head of the Queue so it gets processing before other 
> requests?
> 
> All the Best
> Dave

Consider using NSOperationQueue (OperationQueue if you’re using Swift) instead 
of performSelector:withObject:afterDelay:, and have a look at the queuePriority 
property on Operation/NSOperation. The following code:

> import Foundation
> 
> let op1 = BlockOperation {
>   print("op1")
> }
> 
> let op2 = BlockOperation {
>   print("op2")
> }
> 
> let quitOp = BlockOperation {
>   exit(0)
> }
> 
> quitOp.addDependency(op1)
> quitOp.addDependency(op2)
> 
> op1.queuePriority = .veryLow
> op2.queuePriority = .veryHigh
> 
> OperationQueue.main.addOperations([op1, op2, quitOp], waitUntilFinished: 
> false)
> 
> RunLoop.main.run()

outputs:

> op2
> op1

This shouldn’t be taken as a guarantee, but it does make it more likely that 
your operation will be executed before others.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: Translating KVO-ed property to Swift

2017-04-24 Thread Charles Srstka
> On Apr 24, 2017, at 1:17 PM, Quincey Morris 
> <quinceymor...@rivergatesoftware.com> wrote:
> 
> On Apr 24, 2017, at 10:11 , Charles Srstka <cocoa...@charlessoft.com 
> <mailto:cocoa...@charlessoft.com>> wrote:
>> 
>> What Quincey seemed to be referring to was a property that was not backed by 
>> any kind of persistent value.
> 
> That wasn’t actually the kind of property I had in mind. I was thinking of 
> settable, computed properties that did not depend on the value(s) of other 
> KVO-observable properties. There probably aren’t many plausible *simple* 
> examples, but I was thinking of such cases as when the value is stored in an 
> I/O device rather than RAM, or when the value is retrieved from a server.

In this case, I would try to see if I could find some way to monitor changes in 
the underlying storage, and call the willChange and didChange methods manually 
when changes occur. I’d only make the property dynamic if it was completely 
impossible to do this, and I’d keep this to a last resort. The reason is 
because in this case, the property is not fully KVO-compliant, because its 
value can change without notifications being sent.

I did kind of touch on this with the UserDefaults-example I provided a while 
back. Pretending that NSUserDefaults still notified via NSNotifications only, 
as was the case before native KVO support was added to it, you would register 
for the NSNotification, check whether your default had changed, and fire the 
willSet and didSet notifications once it did. This is a lot more robust than 
depending on the automatic notifications when your property’s value may change 
without going through the property’s setter.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: Translating KVO-ed property to Swift

2017-04-24 Thread Charles Srstka
> On Apr 24, 2017, at 10:07 AM, Richard Charles <rcharles...@gmail.com> wrote:
> 
>> 
>> On Apr 23, 2017, at 11:27 AM, Charles Srstka <cocoa...@charlessoft.com 
>> <mailto:cocoa...@charlessoft.com>> wrote:
>> 
>>> On Apr 20, 2017, at 3:06 PM, Quincey Morris 
>>> <quinceymor...@rivergatesoftware.com 
>>> <mailto:quinceymor...@rivergatesoftware.com>> wrote:
>>> 
>>> Where I disagree is in your much stronger claim that a computed property is 
>>> *necessarily* a dependent property. I think this is just false. The Swift 
>>> distinction between computed and stored properties is syntactic and has 
>>> nothing to do with KVO**. A KVO-observed computed property should 
>>> therefore, according to the documented principle, be marked “dynamic”. For 
>>> anyone following your extended principle, if it’s also a dependent 
>>> property, they can omit the “dynamic”. If not, not.
>> 
>> Do you have any example of a property not backed by anything where KVO even 
>> makes sense? The whole purpose of KVO is to watch changes to values, and if 
>> there’s no value, it seems like the wrong tool.
> 
> I have a property that returns an array. A setter for this property makes no 
> sense. The property returns a collection of managed objects that is the 
> composite value of several to-many relationships.
> 
> This property is KVO compliant and bound to the NSContentArrayBinding of an 
> array controller.
> 
> There is most likely more than one way to do this but I find using bindings 
> convienient. You can bind to a KVO compliant property. You can't bind to a 
> notification.
> 
> This is in an Objective-C project that requires interoperability with a C++ 
> library. So using Swift is not possible but maybe someday it will be.
> 
> --Richard Charles

But it sounds like this property *is* backed by a value. The backing is the 
collection of managed objects. I take it you’re simply watching changes to the 
C++ source data and calling didChange/willChange when appropriate—basically 
translating one type of notification to another. This makes perfect 
sense—although not having a setter, being marked ‘dynamic’ would not change its 
behavior at all.

What Quincey seemed to be referring to was a property that was not backed by 
any kind of persistent value. Presumably, this property would also have a 
setter, since otherwise ‘dynamic’ isn’t really in play. I’m very curious as to 
what the applicability of such a thing would be, because I can’t think of any 
myself.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: Translating KVO-ed property to Swift

2017-04-23 Thread Charles Srstka
Sorry I didn’t get around to replying sooner; I’ve had a busy past few days.

> On Apr 20, 2017, at 3:06 PM, Quincey Morris 
> <quinceymor...@rivergatesoftware.com> wrote:
> 
> On Apr 20, 2017, at 10:24 , Charles Srstka <cocoa...@charlessoft.com 
> <mailto:cocoa...@charlessoft.com>> wrote:
>> 
>> I mean, yes, we could go all the way down to explaining how everything works 
>> in terms of the physics and chemistry of electrons and semiconductors, but 
>> that wouldn’t be very practical, would it?
> 
> I subscribe to the principle already quoted from the documentation: If you 
> KVO-observe a property, mark it “dynamic”. I like this because it is simple 
> and unambiguous. If anyone asked me for advice, I’d say to follow this 
> principle and don’t agonize any further.

It is simple, and it’ll work, and there’s certainly nothing wrong with it. It’s 
a little non-ideal performance-wise, though, which is why I prefer using 
dynamic only where it’s needed.

> As a different discussion, at a different level, I agree that there are 
> scenarios where you can omit “dynamic” and still get all the KVO 
> notifications you wanted. What scenarios? Well, I think the essence of your 
> argument is that it can be omitted for a KVO-observed *dependent* property.

The essence of my argument is pretty simple; it can be omitted for any property 
where willChange and didChange are already being called.

For a dependent property, those calls will be made in your dependency, so you 
don’t need dynamic. For a stored property where you’re calling willChange and 
didChange yourself, you don’t need dynamic. For, I dunno, weird situations 
where willChange and didChange are getting called somewhere else but at the 
appropriate times, you don’t need dynamic. Dynamic is only needed to let Cocoa 
add the willChange and didChange notifications for you.

> That at least sounds pretty plausible to me, and it may even be true by 
> definition. If anyone asked you for advice, then I guess you’d say to accept 
> this as an extension of the documented principle. Me, I’m not 100% certain 
> about this, if for no other reason than the documented principle is 
> future-proof against a change in the way things work where Apple says, “Well, 
> we told to you mark all KVO-observed properties dynamic.” But, people can go 
> for advice where they want.

This isn’t just based on empirical observation, though; it’s based on the 
documentation of the KVO mechanism, which predates Swift by quite a lot. KVO 
isn’t a mysterious black box; the details of it are all available in the 
documentation, and once you understand them, you understand *why* dynamic is 
needed. And once you understand *why* it’s needed, you also will understand 
*where* it’s needed. Personally, I prefer to, when possible, understand the 
reasons behind doing things rather than repeating magical incantations.

As for future-proof, I fully expect that in some future version of Swift (Swift 
5, hopefully, maybe Swift 6), we’ll get a new and improved, Swift-native 
replacement for KVC and KVO and we’ll all be ripping out our existing KVO code 
in favor of that anyway.

> Where I disagree is in your much stronger claim that a computed property is 
> *necessarily* a dependent property. I think this is just false. The Swift 
> distinction between computed and stored properties is syntactic and has 
> nothing to do with KVO**. A KVO-observed computed property should therefore, 
> according to the documented principle, be marked “dynamic”. For anyone 
> following your extended principle, if it’s also a dependent property, they 
> can omit the “dynamic”. If not, not.

Do you have any example of a property not backed by anything where KVO even 
makes sense? The whole purpose of KVO is to watch changes to values, and if 
there’s no value, it seems like the wrong tool.

I mean, sure, I could make this observable:

var whyWouldIObserveThis: Int {
return Int(arc4random())
}

and then send didChange/willChange notifications on a timer or something. 
But... *why?*

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: Translating KVO-ed property to Swift

2017-04-20 Thread Charles Srstka
> On Apr 19, 2017, at 9:12 PM, Quincey Morris 
> <quinceymor...@rivergatesoftware.com> wrote:
> 
> On Apr 19, 2017, at 15:49 , Charles Srstka <cocoa...@charlessoft.com> wrote:
>> 
>> Cocoa automagically does its secret subclass thing to wrap the setter and 
>> call the didChange/willChange calls for any property you didn’t tell it not 
>> to do. It needs the property to be dynamic for this to work. 
> 
> Yes, that’s almost exactly what I said**. But it still doesn’t make the 
> “dynamic” keyword an on/off switch. Again, the KVO notifications aren’t 
> activated *because* the method has the Swift-specific dynamic attribute, but 
> because the method uses Obj-C dispatching. The “dynamic” keyword [currently] 
> forces the method to use Obj-C dispatching, but the reverse isn’t true. In 
> the absence of the keyword, there’s nothing formally stopping the compiler 
> from using Obj-C dispatching if it chooses to.
> 
> At some level, though, I’m prepared to stipulate that it’s a distinction 
> without much practical difference.

The statement didn’t say anything about “dynamic” being an “on/off switch.” The 
statement that you were quibbling was that you can mark a stored property as 
‘dynamic’, and Cocoa will do the rest. It didn’t say anything about what 
*causes* it, it was meant to be a practical guide to how to implement KVO 
properties in Swift. And to make Cocoa automatically handle the 
didChange/willChange calls, you mark a property as dynamic. I mean, yes, we 
could go all the way down to explaining how everything works in terms of the 
physics and chemistry of electrons and semiconductors, but that wouldn’t be 
very practical, would it?

>> I should add that if a computed property needs ‘dynamic’ in order for its 
>> notifications to fire, the property is not properly KVO-compliant.
> 
> It’s impossible to say in general what counts as a change to a mutable 
> property. Indeed it’s perfectly possible for a property to exist for the 
> purpose of generating KVO notifications without having any meaningful value, 
> and there are plenty more un-generalizable considerations:

The entire purpose of KVO is to monitor changes to values. The word “value” is 
literally right there in the title, as well as most of the major APIs that make 
it work. observeValue. willChangeValue. didChangeValue. value(forKey:). 
setValue. keyPathsForValuesAffecting. Using KVO without a meaningful value is, 
frankly, using a hammer to drive in a screw. For a value-less notification, 
something like NSNotificationCenter is a much better choice.

> — It’s up to an individual property (with a meaningful value) to decide 
> whether KVO notifications are issued when the setter is called (in effect, 
> the default case) or when the value actually changes (as in Rick’s original 
> code), or under some other conditions (e.g. I can imagine a property limiting 
> the rate of notifications using a timer).

Which does not require a property to be dynamic, and in fact would require 
*disabling* Cocoa’s use of dynamism for the property, via returning false for 
automaticallyNotifiesObserversOf.

> — There’s no general presumption whether the value returned by the getter is 
> synchronized with the value passed to the setter.

The setter, however, is likely to make some kind of change to the underlying 
storage such that we will be notified of it. And if no such change is made, 
then there is little point in sending change notifications.

> — There’s no general presumption whether the value returned by the getter is 
> synchronized with the notification, in a multi-threaded environment.

Assuming you’re referring to the fact that something in another thread could 
change the property in the middle of your observer, this still has little that 
I can see to do with the ‘dynamic’ keyword.

> — There’s no general presumption that KVO notifications originate in the 
> property's setter at all, or in the setter only.
> 
> Etc. “keyPathsForValuesAffecting…”-style dependencies are just a convenient 
> short-cut to a specific, simple, typical behavior.

Who said there was?

The bottom line with KVO notifications is that you’ll get one when either:
1. willChange and didChange get called for the property you’re 
watching, or
2. willChange and didChange get called for something that the property 
you’re watching is dependent on.

In case 1, you can either call willChange or didChange yourself, or you can let 
Cocoa do it for you. In Swift, you need to mark it ‘dynamic’ for the latter to 
happen.

In case 2, you don’t need willChange or didChange to get called for your 
property, because we will already get notified when the dependency’s willChange 
and didChange get called. In fact, we might not want them to, because it’ll 
cause the notification to double-post—once in the setter, and 

Re: Translating KVO-ed property to Swift

2017-04-19 Thread Charles Srstka
> On Apr 19, 2017, at 4:50 PM, Quincey Morris 
>  wrote:
> 
>> 3. Computed properties do not need to be dynamic, […].
> 
> This is also not exactly true. Computed properties that have only a getter do 
> not need to be dynamic, because they don’t generate any KVO notifications via 
> a setter, and so “dynamic” is irrelevant.
> 
> However, a computed property that has a setter will *not* produce the 
> expected notifications unless it is marked “dynamic”, even if marked “@objc”. 
> (I tested this to be sure.) There’s nothing special about computed vs. stored 
> properties in this regard.

I should add that if a computed property needs ‘dynamic’ in order for its 
notifications to fire, the property is not properly KVO-compliant. There are 
three ways this could happen that I can think of off the top of my head:

Case #1: Derived from another KVO property

> @objc dynamic var foo: String
> 
> @objc var bar: String {
>   get { return self.foo }
>   set { self.foo = newValue }
> }

The above will not fire notifications for bar. Making bar ‘dynamic’ appears to 
fix the problem, but it is in fact still not compliant; if foo changes, bar’s 
value is changed as well, but its notifications will not fire. The proper way 
to fix this is to add keyPathsForValuesAffectingBar.

Case #2: Backed by something not exposed to Objective-C

> enum Option: String {
>   case foo = “Foo"
>   case bar = “Bar"
>   case baz = “Baz"
> }
> 
> var option: Option
> 
> @objc var objcOption: String {
>   get { return self.option.rawValue }
>   set {
>   if let option = Option(rawValue: newValue) {
>   self.option = option
>   }
>   }
> }

The above will not fire notifications for objcOption. Making objcOption 
‘dynamic’ appears to fix the problem, but if option is changed, objcOptions’s 
value will change as well, and its notifications will not fire. The proper way 
to fix this is to add willChangeValue(forKey:) and didChangeValue(forKey:) 
calls in option’s willSet and didSet accessors.

Case #3: It’s backed by something other than a property

> @objc var isFoo: Bool {
>   get { return UserDefaults.bool(forKey: “Foo”) }
>   set { UserDefaults.set(newValue, forKey: “Foo”) }
> }

The above will not fire notifications for isFoo. Making isFoo ‘dynamic’ appears 
to fix the problem, but if the “Foo” defaults key changes by some mechanism 
other than isFoo’s setter, isFoo’s value will have changed, but the 
notifications will not fire. The better solution is to register for changes on 
UserDefaults or NSUserDefaultsController via one of the several available 
mechanisms that Cocoa provides to do that and ensure that isFoo’s clients are 
notified when the underlying value changes.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: Translating KVO-ed property to Swift

2017-04-19 Thread Charles Srstka
> On Apr 19, 2017, at 4:50 PM, Quincey Morris 
> <quinceymor...@rivergatesoftware.com> wrote:
> 
> On Apr 19, 2017, at 10:56 , Charles Srstka <cocoa...@charlessoft.com> wrote:
>> 
>> 2. Stored properties need to call willChangeValue(forKey:) and 
>> didChangeValue(forKey:).
>>  a. In most cases, just add “dynamic” to the property declaration, and 
>> Cocoa will automagically insert the needed calls.
> 
> The problem with saying it this way is that it can be taken to imply that the 
> calls will be inserted statically *into the setter’s implementation*, which 
> is not true. It is true that Cocoa will automagically *execute* the needed 
> calls.
> 
> It also can be taken to imply that Cocoa does this automagically because the 
> property is dynamic, which is also not really true. Cocoa does this because 
> it’s a setter for an Obj-C property which returns true from its corresponding 
> automaticallyNotifiesObserversOfFoo class method. That is, “dynamic” doesn’t 
> turn the automagic behavior off or on, it’s simply a requirement to ensure 
> that the property is fully in the Obj-C domain.

Cocoa automagically does its secret subclass thing to wrap the setter and call 
the didChange/willChange calls for any property you didn’t tell it not to do. 
It needs the property to be dynamic for this to work. Thus, if you add 
“dynamic” to the property declaration, Cocoa will do the rest. That’s really 
all that’s relevant from a usage standpoint.

>> 3. Computed properties do not need to be dynamic, […].
> 
> This is also not exactly true. Computed properties that have only a getter do 
> not need to be dynamic, because they don’t generate any KVO notifications via 
> a setter, and so “dynamic” is irrelevant.
> 
> However, a computed property that has a setter will *not* produce the 
> expected notifications unless it is marked “dynamic”, even if marked “@objc”. 
> (I tested this to be sure.) There’s nothing special about computed vs. stored 
> properties in this regard.
> 
> I think you were “really” talking about derived properties, which are 
> typically computed properties with only a getter, no setter.

Nope, you can have a setter. You just have to make sure you’ve properly set up 
keyPathsForValuesAffecting. Here is some test code you can run yourself 
and verify this:

> import Foundation
> 
> class Foo: NSObject {
>   @objc dynamic var bar: String = ""
>   
>   @objc private static let keyPathsForValuesAffectingBaz: Set = 
> [#keyPath(bar)]
>   @objc var baz: String {
>   get { return self.bar }
>   set { self.bar = newValue }
>   }
>   
>   private var kvoContext = 0
>   
>   override init() {
>   super.init()
>   self.addObserver(self, forKeyPath: #keyPath(baz), options: [], 
> context: )
>   }
>   
>   override func observeValue(forKeyPath keyPath: String?, of object: 
> Any?, change: [NSKeyValueChangeKey : Any]?, context: 
> UnsafeMutableRawPointer?) {
>   if context ==  {
>   print("baz changed to \(self.baz)")
>   } else {
>   super.observeValue(forKeyPath: keyPath, of: object, 
> change: change, context: context)
>   }
>   }
> }
> 
> let foo = Foo()
> 
> foo.bar = "Bar"
> foo.baz = “Baz"

When run, this outputs:

baz changed to Bar
baz changed to Baz

Exactly as you would expect.

> In addition, “dynamic” is documented as needed, in the place I linked to 
> before:
> 
>   
> https://developer.apple.com/library/content/documentation/Swift/Conceptual/BuildingCocoaApps/AdoptingCocoaDesignPatterns.html#//apple_ref/doc/uid/TP40014216-CH7-ID6
> 
> under the heading Key-Value Observing where it says: "Add the dynamic 
> modifier to any property you want to observe.” This may be overly 
> conservative, but it is at least official.
> 
> For all those reasons, I think it’s pointless to try to figure out the 
> contexts where “dynamic” is unnecessary. It seems to me that the best advice 
> is that from the documentation: unconditionally add “dynamic” to any property 
> you want to observe. (Well, in the future, add “@objc dynamic”.)

It’s an oversimplification. If you understand the reasons why the ‘dynamic’ 
keyword is necessary, you will also be able to identify where it serves solely 
as unnecessary overhead.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: Translating KVO-ed property to Swift

2017-04-19 Thread Charles Srstka
> On Apr 17, 2017, at 7:40 AM, Jean-Daniel  wrote:
> 
>> Le 17 avr. 2017 à 10:52, Quincey Morris > > a écrit :
>> 
>> On Apr 17, 2017, at 01:43 , Jean-Daniel >  > >> wrote:
>>> 
>>> var version: String? {
>> 
>> A slight correction: this declaration actually must be:
>> 
>>> dynamic var version: String? {
>> 
>> 
>> otherwise KVO isn’t guaranteed to work in Swift.
> 
> This is a good practice, but I don’t think this is required for computed 
> property, especially if you take care of willChange/didChange manually, as 
> the OP does.

Here’s the set of rules I recommend for writing KVO-compliant properties in 
Swift:

1. Always put @objc in front of every declaration involved, whether it’s the 
property itself or the static properties that are there to support it.

2. Stored properties need to call willChangeValue(forKey:) and 
didChangeValue(forKey:).
a. In most cases, just add “dynamic” to the property declaration, and 
Cocoa will automagically insert the needed calls.
b. If you call willChangeValue and didChangeValue manually, add the 
following static property, changing Foo to the property’s name. Since this is 
easy to misspell accidentally, it’s best to make an Xcode code snippet for it.

@objc private static let automaticallyNotifiesObserversOfFoo = false

3. Computed properties do not need to be dynamic, but should register their 
dependencies. The properties that form these dependencies also need to be 
KVO-compliant. To register dependencies, add the following static property. 
This is also helpful to set as an Xcode snippet to avoid typos.

@objc private static let keyPathsForValuesAffectingFoo: Set = 
[#keyPath(bar)]

The snippet above tells Cocoa that the KVO-compliant property “foo” depends on 
the KVO-compliant property “bar”, meaning that if “bar” changes, “foo”’s 
observers will be notified as well.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: Translating KVO-ed property to Swift

2017-04-17 Thread Charles Srstka
> On Apr 17, 2017, at 1:09 PM, Quincey Morris 
> <quinceymor...@rivergatesoftware.com> wrote:
> 
> On Apr 17, 2017, at 05:40 , Jean-Daniel <mail...@xenonium.com> wrote:
> 
>> This is a good practice, but I don’t think this is required for computed 
>> property, especially if you take care of willChange/didChange manually, as 
>> the OP does.
> 
> Here is what the Swift interoperability documentation says 
> (https://developer.apple.com/library/content/documentation/Swift/Conceptual/BuildingCocoaApps/AdoptingCocoaDesignPatterns.html):

And the reason for this is because Cocoa swizzles the accessor and adds the 
willChangeValue() and didChangeValue() calls. If you’re calling these yourself 
(or if you’re a computed property that registers its dependencies via 
keyPathsForValuesAffecting methods), you don’t need dynamic.

>> "You can use key-value observing with a Swift class, as long as the class 
>> inherits from the NSObject class. You can use these three steps to implement 
>> key-value observing in Swift.
>> 
>> "1. Add the dynamic modifier to any property you want to observe. […]”
> 
> Here is what the Swift language documentation says 
> (https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Declarations.html):
> 
>> “dynamic”
>> 
>> "Apply this modifier to any member of a class that can be represented by 
>> Objective-C. When you mark a member declaration with the dynamic modifier, 
>> access to that member is always dynamically dispatched using the Objective-C 
>> runtime. Access to that member is never inlined or devirtualized by the 
>> compiler.”
> 
> That is, unless you specify “dynamic” there’s no *guarantee* that invocations 
> to the property accessors will use obj_msgSend, and since there’s no way in 
> Swift to guarantee that obj_msgSend *won’t* be used for the property, the 
> outcome for automatic KVO is unpredictable. 

You cannot guarantee that the property will be called via objc_msgSend, which 
is important if you’re relying on the swizzled accessor to send the property 
notifications. If you’re sending them yourself, it doesn’t matter one way or 
another how the property was called, as long as you add @objc so that clients 
that do expect to be able to use objc_msgSend (most importantly, NSObject’s 
observation support) can do it.

> On Apr 17, 2017, at 08:07 , Charles Srstka <cocoa...@charlessoft.com> wrote:
>> 
>> // Note that this doesn’t need to be dynamic, since we are not relying on 
>> Cocoa’s built-in automatic swizzling,
>> // which is only needed if we are not calling willChangeValue(forKey:) and 
>> didChangeValue(forKey:) ourselves.
>> @objc var version: String {
>>willSet {
>>// Send the willChange notification, if the value is different from 
>> its old value.
>>if newValue != self.version {
>>self.willChangeValue(forKey: #keyPath(version))
>>}
>>}
>>didSet {
>>// Send the didChange notification, if the value is different from 
>> its old value.
>>if oldValue != self.version {
>>self.didChangeValue(forKey: #keyPath(version))
>>}
>>}
>> }
> 
> I tested what happens (in Swift 3.1, Xcode 8.3.1) using this code:
> 
>> private var versionContext = 0
>> 
>> class ViewController: NSViewController {
>>  @objc /*dynamic*/ var version: String = “” {
>>  willSet {
>>  if newValue != self.version {
>>  self.willChangeValue (forKey: 
>> #keyPath(version)) }
>>  }
>>  didSet {
>>  if oldValue != self.version {
>>  self.didChangeValue (forKey: #keyPath(version)) 
>> }
>>  }
>>  }
>>  override func viewDidLoad () {
>>  super.viewDidLoad ()
>>  addObserver (self, forKeyPath: #keyPath(version), options: [], 
>> context: )
>>  }
>>  override func observeValue (forKeyPath keyPath: String?,  of object: 
>> Any?,  change: [NSKeyValueChangeKey : Any]?,  context: 
>> UnsafeMutableRawPointer?) {
>>  print ("observedValue for \(version)")
>>  }
>>  @IBAction func buttonClicked (_ sender: Any?) { // There’s a button in 
>> the UI hooked up to this
>>  version = version == "" ? "1" : "\(version)"
>>  }
>> }
> 
> This version of the code (with “dynamic” commented out) displays the observer 
> message once, as des

Re: Translating KVO-ed property to Swift

2017-04-17 Thread Charles Srstka
> On Apr 17, 2017, at 3:24 AM, Rick Mann  wrote:
> 
> I have a number of properties in Objective-C written like this, 
> short-circuiting notifications when the value doesn't change:
> 
> -
> @synthesize version = mVersion
> 
> - (void)
> setVersion: (NSString *) inVersion
> {
>if (inVersion == nil && mVersion == nil)
>{
>return;
>}
>if ([inVersion isEqualToString: mVersion])
>{
>return;
>}
> 
>[self willChangeValueForKey: @"version"];
>mVersion = inVersion;
>[self didChangeValueForKey: @"version"];
> }
> -
> 
> Now I want to translate this method into Swift. Thing is, AFAIK you can't 
> name the ivar created for a property. Is there a way to translate this to 
> swift?

I’ve been converting a lot of KVO properties to Swift lately. Here’s how I’d do 
this:

// Only needed if the property will be accessed by Objective-C code, since 
Swift code won’t see the swizzled accessors anyway for a non-dynamic property.
// @objc annotation is needed on every method we write here, since otherwise 
it’ll quit working when @objc inference is removed in Swift 4 (SE-0160)
@objc private static let automaticallyNotifiesObserversOfVersion: Bool = false

// Our actual version property. If you want, you can create a private property 
named “mVersion” and it will function like an instance variable.
// But I’d probably just use willSet and didSet.
// Note that this doesn’t need to be dynamic, since we are not relying on 
Cocoa’s built-in automatic swizzling,
// which is only needed if we are not calling willChangeValue(forKey:) and 
didChangeValue(forKey:) ourselves.
@objc var version: String {
willSet {
// Send the willChange notification, if the value is different from its 
old value.
if newValue != self.version {
self.willChangeValue(forKey: #keyPath(version))
}
}
didSet {
// Send the didChange notification, if the value is different from its 
old value.
if oldValue != self.version {
self.didChangeValue(forKey: #keyPath(version))
}
}
}

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: What do the font-related Cocoa Bindings in NSTableView and NSTableColumn do?

2017-04-05 Thread Charles Srstka
> On Apr 5, 2017, at 4:08 PM, Daryle Walker <dary...@mac.com> wrote:
> 
>> 
>> On Apr 5, 2017, at 12:19 PM, Charles Srstka <cocoa...@charlessoft.com 
>> <mailto:cocoa...@charlessoft.com>> wrote:
>> 
>> 
>> Actually, while NSTableCellView won’t bind to *most* things outside of the 
>> table view, there is an exception for the table’s delegate. So, if you set 
>> the table’s delegate to File’s Owner, and then bind the NSTableCellView’s 
>> ‘font’ binding to File’s Owner, it should work.*
>> 
>> *But only in a XIB file. In a storyboard, the XIB compiler will get stuck in 
>> an infinite loop which will continue even after you click the “Stop” button, 
>> grabbing more and more RAM surreptitiously in the background until your Mac 
>> runs out of swap space and you’re forced to do a hard reboot. Hooray for 
>> Xcode!
> 
> I am using a storyboard. And this hang upon XIB-compilation is what happens 
> whenever I try font-binding.

I filed a radar (rdar://31468797 ), so hopefully this will 
eventually be fixed.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: What do the font-related Cocoa Bindings in NSTableView and NSTableColumn do?

2017-04-05 Thread Charles Srstka
> On Apr 5, 2017, at 8:38 AM, Keary Suska  wrote:
> 
>> 
>> On Apr 4, 2017, at 4:34 PM, Daryle Walker > > wrote:
>> 
>> 
>>> On Apr 4, 2017, at 9:57 AM, Keary Suska >> > wrote:
>>> 
>>> 
 On Apr 3, 2017, at 5:40 PM, Daryle Walker > wrote:
 
 Is there a way to affect the font of a table cell via Bindings? The few 
 times I tried, at the NSTextField level (NSTableCellView does not have any 
 font-related Bindings), resulted in Xcode’s XIB compiler jamming. (I 
 always cancel and take out the change.)
>>> 
>>> Remember that NSTableCellView subviews cannot bind outside of the 
>>> NSTableCellView. The easiest approach is to have the font a property on the 
>>> model object set as NSTableCellView’s objectValue, and bind to that.
>> 
>> My model just stores strings.
> 
> So? Do you have a religious belief against mixing class properties? (Sorry, 
> couldn’t resist ;-) If the issue is persistence, the value would be transient 
> and not stored (as it is stored elsewhere).
> 
>> So, I would have to make a value-transformer that reads the font preference 
>> from the user-defaults and create a attributed-string with the model string 
>> in the desired font?
> 
> You could, but you wouldn’t be able to easily update the UI when the font is 
> changed.

Actually, while NSTableCellView won’t bind to *most* things outside of the 
table view, there is an exception for the table’s delegate. So, if you set the 
table’s delegate to File’s Owner, and then bind the NSTableCellView’s ‘font’ 
binding to File’s Owner, it should work.*

*But only in a XIB file. In a storyboard, the XIB compiler will get stuck in an 
infinite loop which will continue even after you click the “Stop” button, 
grabbing more and more RAM surreptitiously in the background until your Mac 
runs out of swap space and you’re forced to do a hard reboot. Hooray for Xcode!

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: Is there a way to pluralize menu items?

2017-04-05 Thread Charles Srstka
> On Apr 5, 2017, at 8:10 AM, Steve Mills  wrote:
> 
> On Apr 4, 2017, at 22:09:34, Daryle Walker  > wrote:
>> 
>> I have a menu item named like “Remove Item”. But I added support for 
>> multiple-selection in the table-view. So is there a way to change the menu 
>> item to “Remove Items” when more than one item is selected. I think there’s 
>> a “stringdict” format that can handle all sorts of plural rules (some 
>> locales do more than singular vs. non-singular in English). Can that help 
>> here?
> 
> Add a validateMenuItem: method to set the title based on the number of items.
> 
> --
> Steve Mills
> Drummer, Mac geek

The other thing you can do is to bind the menu item’s “title” binding to a 
dynamic property, and update that property as appropriate when the number of 
items changes.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: Can't use +initialize, now what?

2017-03-29 Thread Charles Srstka
> On Mar 29, 2017, at 3:41 PM, Greg Parker <gpar...@apple.com> wrote:
> 
>> On Mar 29, 2017, at 9:02 AM, Charles Srstka <cocoa...@charlessoft.com 
>> <mailto:cocoa...@charlessoft.com>> wrote:
>> 
>>> On Mar 29, 2017, at 10:51 AM, Jens Alfke <j...@mooseyard.com 
>>> <mailto:j...@mooseyard.com>> wrote:
>>> 
>>>> On Mar 29, 2017, at 6:57 AM, Daryle Walker <dary...@mac.com 
>>>> <mailto:dary...@mac.com> <mailto:dary...@mac.com 
>>>> <mailto:dary...@mac.com>>> wrote:
>>>> 
>>>> Now the new Xcode release notes say that “• Swift now warns when an 
>>>> NSObject subclass attempts to override the initialize class method, 
>>>> because Swift can't guarantee that the Objective-C method will be called. 
>>>> (28954946)”
>>> 
>>> Huh, I haven’t heard of that. And I’m confused by “the Objective-C method” 
>>> — what’s that? Not the +initialize method being compiled, because that’s in 
>>> Swift. The superclass method?
>>> 
>>> Guess I’ll follow that Radar link and read the bug report myself. Oh, wait. 
>>> :(
>> 
>> You actually can this time, since Swift’s bug reporter is actually open to 
>> the public. https://bugs.swift.org/browse/SR-3114 
>> <https://bugs.swift.org/browse/SR-3114><https://bugs.swift.org/browse/SR-3114
>>  <https://bugs.swift.org/browse/SR-3114>>
>> 
>> Basically, with Whole Module Optimization turned on, +initialize wasn’t 
>> getting called. Their solution was to just get rid of +initialize.
> 
> You don't even need WMO. Many arrangements of Swift code can bypass ObjC 
> +initialize.
> 
> Invocation of +initialize is a feature of objc_msgSend(). Swift code does not 
> always use objc_msgSend() when calling methods: some methods are inlined, 
> some are called via virtual table, some are called directly. None of these 
> paths will provoke +initialize. 
> 
> Changing Swift's generated code to guarantee +initialize would be 
> prohibitively expensive. Imagine an is-initialized check in front of every 
> inlined call. It would be more expensive than +initialize in ObjC because 
> +initialize checking is free once you pay the cost of objc_msgSend(). (The 
> ObjC runtime checks +initialize on uncached dispatch, and never caches 
> anything until +initialize completes. Most dispatches are cached so they pay 
> nothing for +initialize support.)
> 
> +initialize in Swift isn't safe and is too expensive to make safe, so we're 
> taking it away instead.

I wonder if an equivalent Swift-native feature could be added, something like a 
typeInit block? If the block weren’t there, nothing special would happen, and 
if the block were present, the compiler could basically generate the code in 
the example I gave, but add the static var access to the front of every 
initializer and static/class member. That shouldn’t impact performance too 
much, and wouldn’t impact at all in the case that there’s no type initializer.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: Can't use +initialize, now what?

2017-03-29 Thread Charles Srstka
> On Mar 29, 2017, at 10:51 AM, Jens Alfke  wrote:
> 
>> On Mar 29, 2017, at 6:57 AM, Daryle Walker > > wrote:
>> 
>> Sometimes, I see something in Apple’s AppKit/Foundation reference site that 
>> mentions that their technique should be loaded early in the program by 
>> putting it in the class’s “+initiallize” method.
> 
> A +initialize method doesn’t necessarily run early in the program; it runs 
> before the first time a method of that class is called. But that class might 
> not be called until later in the process, or never. So +initialize is useful 
> for setting up state that this specific class will depend on — like 
> initializing static variables — but not for program-wide dependencies.
> 
> There’s a more obscure method +load that _does_ get called when the process 
> starts up (at roughly the same time as C++ static initializer methods.) Its 
> use is discouraged because doing stuff at launch time is bad for 
> responsiveness, and because it’s easy to run into problems with dependencies 
> on other stuff being initialized already, like if your +load method calls 
> something in AppKit that hasn’t been initialized yet because _its_ +load 
> method runs after yours…

+load isn’t exposed to Swift either, so that’s not going to work either. You’re 
going to have to roll your own replacement for +initialize. Here’s how I’ve 
been doing it:

class Foo {
private static let _classInitializer: Void = {
// do your initialization here
}()

init() {
// all static variables are lazy, so be sure not to forget to put this 
at the top of *all* your designated initializers or it won’t happen
_ = Foo._classInitializer
}
}

This will ensure that your initialization code will run the first time an 
object of the class is created, which is similar to what +initialize does (but 
not exact, I know).

>> Now the new Xcode release notes say that “• Swift now warns when an NSObject 
>> subclass attempts to override the initialize class method, because Swift 
>> can't guarantee that the Objective-C method will be called. (28954946)”
> 
> Huh, I haven’t heard of that. And I’m confused by “the Objective-C method” — 
> what’s that? Not the +initialize method being compiled, because that’s in 
> Swift. The superclass method?
> 
> Guess I’ll follow that Radar link and read the bug report myself. Oh, wait. :(

You actually can this time, since Swift’s bug reporter is actually open to the 
public. https://bugs.swift.org/browse/SR-3114 


Basically, with Whole Module Optimization turned on, +initialize wasn’t getting 
called. Their solution was to just get rid of +initialize.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: Unicode filenames with Apple File System and UIManagedDocument

2017-03-23 Thread Charles Srstka
> On Mar 23, 2017, at 3:50 AM, Alastair Houghton  
> wrote:
> 
> On 22 Mar 2017, at 19:13, Chris Ridd  > wrote:
>> 
>>> On 22 Mar 2017, at 09:05, Alastair Houghton >> > wrote:
>>> 
>>> In the context of filesystems (and specifically filenames), the phrases 
>>> “bag of bytes” and “bunch of bytes” have a fairly specific meaning.  The 
>>> point is that the filesystem doesn’t inspect the bytes it’s given, and 
>>> doesn’t care what they represent (about the only exception is that it 
>>> probably doesn’t support embedded NULs).  It isn’t suggesting that the 
>>> names are treated as an unordered set of bytes (that’d just be silly).  
>>> It’s just expressing the fact that the filesystem doesn’t care what they 
>>> are - it may compare them, and if it does so, it will use binary ordering 
>>> (not some other collation sequence) and won’t worry about things like case 
>>> or encoding at all.
>> 
>> That doesn’t sound sensible at all. It means you can create a filename with 
>> a byte sequence that isn’t valid UTF-8 and which likely then cannot be 
>> accessed by MacOS/iOS processes.
> 
> That isn’t possible on macOS - there’s a percent escaping mechanism built in 
> to the kernel to prevent this problem.
> 
>> It means that you could create multiple files with the “same" name, and that 
>> doesn’t sound like a win either. e.g. Aandi’s examples of LATIN SMALL LETTER 
>> E (U+0065)
>> COMBINING ACUTE ACCENT (U+0301) and LATIN SMALL LETTER E WITH ACUTE (U+00E9)
> 
> Yes, it does.
> 
>> How can a “next gen” filesystem avoid using Unicode rules when handling 
>> filenames?
> 
> Well, if I had designed it, it wouldn’t.  But I didn’t.
> 
> To be fair, I can see arguments in favour of the bunch of bytes approach; the 
> existing approach has created a problem in HFS+, in that the normalisation is 
> essentially fixed for all time, and doesn’t correspond to the current version 
> of Unicode.  It’s actually worse than it might be, because (IIRC) they fixed 
> the normalisation *before* Unicode adopted a stability policy for 
> normalisation...
> 
> But if the filesystem (or kernel) isn’t doing it, then IMO the Cocoa 
> frameworks certainly should.

Shouldn’t the VFS layer actually be doing this? It is part of its whole raison 
d’être, no? Just have -[NSURL fileSystemRepresentation] normalize things 
according to the correct Unicode rules, and let the VFS layer translate that to 
HFS+’s normalization style when dealing with HFS+.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: Unicode filenames with Apple File System and UIManagedDocument

2017-03-21 Thread Charles Srstka
> On Mar 21, 2017, at 9:13 AM, davel...@mac.com wrote:
> 
>> 
>> On Mar 21, 2017, at 8:33 AM, Jean-Daniel > > wrote:
>> 
>> 
>>> Le 21 mars 2017 à 12:03, davel...@mac.com a écrit :
>>> 
 
 On Mar 21, 2017, at 1:06 AM, Jens Alfke  wrote:
 
 
> On Mar 20, 2017, at 2:23 PM, davel...@mac.com wrote:
> 
> NSURL *url = [[self courseDirectory] URLByAppendingPathComponent:name];
 
 There’s nothing wrong with that call; it’s the canonical way to add a path 
 component to a URL, filesystem or not.
 
> NSURL *url = [NSURL fileURLWithFileSystemRepresentation:[name 
> fileSystemRepresentation] isDirectory:YES relativeToURL:[self 
> courseDirectory]];
 
 This call doesn’t make sense. You’re converting to filesystem 
 representation and then back again, for no reason.
 
 What Apple suggested is to Unicode-normalize the filename before adding it 
 to the URL. Did you try doing that?
 
 —Jens
>>> 
>>> Jens,
>>> 
>>> I’m trying to find out what that means. Someone suggested off-list to me 
>>> that I should be calling this:
>>> 
>>> https://developer.apple.com/reference/foundation/nsstring/1409474-decomposedstringwithcanonicalmap?language=objc
>>> 
>>> Is that correct?
>>> 
>>> So based on that, I think it means I should do:
>>> 
>>> NSURL *url = [[self courseDirectory] 
>>> URLByAppendingPathComponent:name.decomposedStringWithCanonicalMapping];
>>> 
>>> Thanks,
>>> Dave Reed
>>> 
>> 
>> This is what the reply suggest but that make no sens for me. If you are 
>> accessing the file using URL, that the work of the framework to convert the 
>> URL into the right file system representation.
>> 
>> That said, if using name.decomposedStringWithCanonicalMapping fix your 
>> problem, so go with it.
> 
> Unfortunately, I can't tell. One user told me he couldn't open his files 
> (with Arabic names) after upgrading to iOS 10.3 public beta. He then changed 
> the names to English names and was able to open the files. He sent me some 
> sample files that I can open (but they were zipped by my app and then 
> unzipped by me) so I honestly can't tell if any of these changes have 
> different effects. With all the options I've tried, I can open the files on 
> my 10.2 and my 10.3 developer device.
> 
> If he creates files with Arabic names on 10.3 he can open them so something 
> happened in the 10.2 to 10.3 (which is why I suspect APFS) upgrade that 
> prevents files created with 10.2 from being opened with 10.3.
> 
> My plan to test it is to take a file created with 10.2 using an Arabic name 
> and see what happens when I upgrade my regular phone to 10.3 but obviously 
> that's time consuming and I only plan to do that upgrade once since it's a 
> pain to downgrade (and not certain it would be possible with the APFS change).
> 
> That's why I keep emailing about this - I can't test it and can't find 
> specific documentation from Apple that says exactly how to create a NSURL 
> from a NSString that may contain Unicode characters.
> 
> Thanks,
> Dave Reed

Maybe you could make a debug build and send it to him (can you do that on iOS?) 
with some code that logs the raw Unicode characters of the filenames in the 
directory, without the name getting changed/decomposed/recomposed/etc by the 
zip/unzip process, and have him send you the output. Something like:

void LogFilenames(NSURL *url) {
DIR *dir = opendir(url.fileSystemRepresentation);

struct dirent *file;
while ((file = readdir(dir))) {
NSData *nameData = [[NSData alloc] initWithBytes:file->d_name 
length:file->d_namlen];

NSLog(@"%@", nameData);
}

closedir(dir);
}

This’ll be in UTF-8 instead of the underlying UTF-16, of course, but it should 
still be useful in figuring out what’s going on.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: why use extern "C"

2017-03-07 Thread Charles Srstka
> On Mar 7, 2017, at 11:42 AM, Aandi Inston  wrote:
> 
> (You should not see // in this section, because in pure C it is forbidden).


This is not true with the latest versions of the C standard. Both C99 and C11 
support inline // comments. The only case where // is not allowed is if someone 
is using a compiler that does not yet support C99, but even in that case, many 
such compilers include non-standard support for //.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: curious: if not file references, what?

2017-01-20 Thread Charles Srstka
> On Jan 20, 2017, at 10:24 PM, Quincey Morris 
>  wrote:
> 
> It’s an interesting question whether file-references use inode numbers. Some 
> file systems don’t have them, so (I assume) they’re invented when such a file 
> system is mounted, but they’re not necessarily assigned permanently across 
> mounts. (I believe Apple documentation says not rely on the file number 
> returned by NSURL metadata methods being stable across mounts.) Even when 
> they’re baked into the file system, it’s not obvious what the semantics are 
> when a volume is copied, or a volume is restored from backup. Perhaps someone 
> else on this list is better informed on the subject than I am.

Actually, this is a common misconception; file references do *not* use inode 
numbers; they refer to CNIDs, which are a separate number stored in the catalog 
file. Inodes refer to raw file data on the disk; CNIDs point instead to a 
particular catalog node. You can have two or more hard links that all point to 
a specific file, but they’ll all have separate CNIDs, and if you delete one of 
them, you’ll break any file references pointing to that particular node.

Note that this is all HFS(+)-specific. APFS may be implemented differently, 
although in my limited testing, it appears to behave the same.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: On NSIncrementalStore UUID Uniqueness

2017-01-19 Thread Charles Srstka
> On Jan 19, 2017, at 3:18 PM, Daryle Walker <dary...@mac.com> wrote:
> 
> 
>> On Jan 16, 2017, at 12:08 PM, Charles Srstka <cocoa...@charlessoft.com 
>> <mailto:cocoa...@charlessoft.com>> wrote:
>> 
>>> On Jan 14, 2017, at 4:41 AM, Daryle Walker <dary...@mac.com 
>>> <mailto:dary...@mac.com>> wrote:
>>> 
>>> Could I base the UUID off a hash of the URL? Maybe, but it wouldn’t survive 
>>> file moves. There are file references in macOS, which would be more stable, 
>>> but I read that there’s a bug in the URL class where it would degrade 
>>> file-reference URLs to standard-file URLs, so that’ll be problematic. 
>>> Another solution would to create bookmark data from a file URL and take a 
>>> hash of that. But are multiple bookmark data blocks of the same file URL 
>>> consistent enough for this idea to work?
>> 
>> The thing with file reference URLs degrading to file path URLs is in the 
>> Swift is actually not a bug, it’s deliberate 
>> (https://bugs.swift.org/browse/SR-2728 
>> <https://bugs.swift.org/browse/SR-2728>). The Swift team decided that file 
>> reference URLs are not appropriate for the Swift URL value type. However, if 
>> you’re using Objective-C, file reference URLs will still work fine, and you 
>> can always make an Objective-C wrapper that stores a file reference URL and 
>> use that from Swift.
> 
> I looked at some code that gives a workaround for the file-reference URL 
> problem. It grabs the reference ID as a 128-bit value, dumps it into 2 64-bit 
> values, then sprinkles those onto a URL string template. Since UUIDs are 
> 128-bit values, I could just copy a reference ID directly into a UUID. 
> However it means existing files would have a different style, possibly 
> overlapping, than new files (which would take a random UUID). Maybe it’ll be 
> better to always use a random UUID, the implementers do in practice.
> 
> — 
> Daryle Walker
> Mac, Internet, and Video Game Junkie
> darylew AT mac DOT com 

That workaround relies on private implementation details, so I wouldn’t 
recommend it. I’d rather just wrap an NSURL within an Objective-C type and then 
call that from Swift (which is what I do in my code).

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: On NSIncrementalStore UUID Uniqueness

2017-01-19 Thread Charles Srstka
> On Jan 16, 2017, at 12:48 PM, Quincey Morris 
> <quinceymor...@rivergatesoftware.com> wrote:
> 
> On Jan 16, 2017, at 09:08 , Charles Srstka <cocoa...@charlessoft.com 
> <mailto:cocoa...@charlessoft.com>> wrote:
>> 
>> The thing with file reference URLs degrading to file path URLs is in the 
>> Swift is actually not a bug, it’s deliberate 
>> (https://bugs.swift.org/browse/SR-2728 
>> <https://bugs.swift.org/browse/SR-2728>). The Swift team decided that file 
>> reference URLs are not appropriate for the Swift URL value type.
> 
> Does the given justification make any sense to you? It certainly makes no 
> sense to me. Perhaps I’m missing something, but the discussion seems to me to 
> conflate the idea of a reference type in Swift with the concept of 
> “referencing” in the world in general:
> 
>> “The[y] are both technically a different type in spirit[**] and they 
>> actually behave much more like a reference type than a structure.”
> 
> 
> By analogy, this is like saying that the Swift String type is good for 
> representing people’s names, but that Obj-C NSString should be used for 
> representing [US] people’s social security numbers, because a SSN is more 
> like a reference than a value.
> 
> In fact, URLs *are* strings — URLs as defined by the RFC, I mean — and that 
> takes the semantics of relating the string to the resource that the string 
> locates outside the scope of the representation itself.
> 
> Perhaps the problem is that file reference URLs don’t have an eternal, unique 
> string representation — that storing and reconstituting a file reference URL 
> may produce a different string? In that case, it’s the URL (the value, not 
> the type) that’s broken, and it’s just as broken in Obj-C as Swift.
> 
> 
> ** Incidentally, they aren’t a different *type* in spirit. File URLs and file 
> reference URLs are both URLs: uniform [syntactically conformant with the RFC] 
> resource [file, in this case] locators [specifiers of where to find]. The 
> difference is in the semantics of the file system, which really has nothing 
> to do with the syntax of the URL.

This post from Apple clarified their reasoning a bit:

https://lists.swift.org/pipermail/swift-corelibs-dev/Week-of-Mon-20161205/001052.html
 
<https://lists.swift.org/pipermail/swift-corelibs-dev/Week-of-Mon-20161205/001052.html>

Basically, they wanted to get rid of the optionality on many of URL’s 
properties; in Swift 2, .path was optional, .lastPathComponent was optional, 
and possibly some others as well. Apparently the only times those methods ever 
returned nil was when the URL in question was a file reference URL; in Swift 3, 
those methods are no longer optional, but file reference URLs are no longer 
supported. :-/

The part of the message that I find ominous is where he says “If references 
were still important”. When you start hearing language like that from Apple, 
it’s usually a sign that they consider the feature no longer relevant and soon 
to be axed. File references were always a key differentiator in the Mac user 
experience, and it would be very sad to see them go.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: On NSIncrementalStore UUID Uniqueness

2017-01-16 Thread Charles Srstka
> On Jan 14, 2017, at 4:41 AM, Daryle Walker  wrote:
> 
> Could I base the UUID off a hash of the URL? Maybe, but it wouldn’t survive 
> file moves. There are file references in macOS, which would be more stable, 
> but I read that there’s a bug in the URL class where it would degrade 
> file-reference URLs to standard-file URLs, so that’ll be problematic. Another 
> solution would to create bookmark data from a file URL and take a hash of 
> that. But are multiple bookmark data blocks of the same file URL consistent 
> enough for this idea to work?

The thing with file reference URLs degrading to file path URLs is in the Swift 
is actually not a bug, it’s deliberate (https://bugs.swift.org/browse/SR-2728 
). The Swift team decided that file 
reference URLs are not appropriate for the Swift URL value type. However, if 
you’re using Objective-C, file reference URLs will still work fine, and you can 
always make an Objective-C wrapper that stores a file reference URL and use 
that from Swift.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: What do NSArrayController, etc. do for me?

2017-01-13 Thread Charles Srstka
> On Jan 13, 2017, at 6:39 AM, Daryle Walker  > wrote:
> 
> If my data model supports KVC/KVO, it seems like I should be able to bind my 
> views to my data directly via Cocoa Bindings, without using NSArrayController 
> or NSObjectController or the like. What advantage do those classes give me?

I just realized you were asking about NSObjectController as well, not just 
NSArrayController. What does NSObjectController do? Well, not a lot, but what 
it does is pretty helpful:

- One minor benefit NSObjectController has is that if you end up with reference 
cycles caused by the bindings system, which is a problem I’ve run into from 
time to time, you can just set the object controller’s content to nil in 
windowWillClose: or a similar place, and break everything’s bindings at once so 
they won’t interfere with the teardown. However, by far the most important 
feature of NSObjectController is:

- NSEditor support 
(https://developer.apple.com/reference/appkit/1654405-nseditor 
). This gives 
you a quick and easy way to solve a very annoying problem. Try building this 
simple application from the Xcode non-storyboard template:

https://gist.github.com/anonymous/207330c13c9144c52381d31421574777 


Try making this application, then binding a text field directly to 
AppDelegate’s “foo” property. Then, connect a button to the saveOrSomething: 
method. Now, build and run the app, type something into the text field, and 
click the button. What do you get? Well, chances are, you saw this:

as this is clicked, foo is ''

The didSet on foo was never called, foo was never updated, and consequently 
when you clicked your save button, out-of-date information got saved. Why is 
this? Because NSTextField doesn’t actually update its bindings until editing 
*ends*, either by the user moving the focus to another UI element by clicking 
on another text field or something, or by the user hitting Return. If you hit 
the Return key after typing something in the field, and *then* hit the button, 
you’ll get the behavior you expect:

did set foo to This is a test
as this is clicked, foo is 'This is a test'

However, this is a pretty annoying UI to use, because it’s very easy to forget 
to end editing before performing some action that depends on the results. You 
can end up thinking you were done with something, closing a document, then 
having to go back and set things up again. If you’ve used macOS/OS X for a long 
time, you’ve probably used a few apps that work like this (Xcode suffered from 
this behavior in certain places for a part of its development), and you’ll know 
how aggravating this can be.

Anyway, NSObjectController can come to our rescue. Change the above code to 
this:

https://gist.github.com/anonymous/c30df983f7603c04cf186b6499c7fac1 


Bind the text field to the object controller instead of to AppDelegate, build 
and run. Type something in the text field, don’t hit Return, and click the 
button. You’ll get:

did set foo to this is a test
as this is clicked, foo is 'this is a test'

Now, when your save method is called, anything that was currently being 
operated upon by a UI element will be updated for you, ensuring that your 
actual save operation writes up-to-date data. Nice!

Note: If you’re using storyboards instead of old-school XIB files, your “File’s 
Owner” will, in most places, be a view controller. NSViewController supports 
the NSEditor methods itself, including commitEditing(), so in this case you 
don’t need an NSObjectController; you can just bind straight to the view 
controller and call commitEditing() on it when necessary. NSObjectController is 
handy in situations where you don’t have an NSViewController, though.

Charles
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: What do NSArrayController, etc. do for me?

2017-01-13 Thread Charles Srstka
> On Jan 13, 2017, at 6:39 AM, Daryle Walker  wrote:
> 
> If my data model supports KVC/KVO, it seems like I should be able to bind my 
> views to my data directly via Cocoa Bindings, without using NSArrayController 
> or NSObjectController or the like. What advantage do those classes give me?
> 
> Sent from my iPhone

What does NSArrayController do? A heck of a lot:

- Automatic propagation of an NSTableView without your having to implement a 
data source.

- Automatic handling of sorting. So, if you click on a table header, that 
column is sorted for you without your having to worry about it. This is fairly 
sophisticated, as well; If you had column A selected before you clicked on 
column B, it will remember that, so two items that have an identical value for 
column B will get sorted according to their values in column A.

- Automatic selection management. So, you can bind a UI element to the array 
controller’s selected object, and that UI element’s content will change as the 
array controller’s selection changes. Pretty handy for implementing something 
like Mail.app’s UI where selecting a different e-mail message in the left-hand 
pane updates the right-hand pane with the contents of that message.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: Opposite of windowDidLoad

2017-01-12 Thread Charles Srstka
> On Jan 12, 2017, at 12:53 PM, Quincey Morris 
>  wrote:
> 
> windowWillClose is an acceptable place to tear down the binding only if (a) 
> the thing bound, and the thing bound to, still exist, and (b) there is no 
> chance that the window will be re-opened. Both of those are typically true, 
> but it does depend on what you’re doing.
> 
> Window dealloc/deinit is also a possible time, but again you need to be sure 
> that the relevant objects still exist, probably by keeping strong references 
> to them in the window controller itself (and again it depends on what you’re 
> doing).

The nice thing about windowWillClose for this is that if the binding ends up 
retaining your window controller somehow, you don’t end up with a retain cycle.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: AVSimplePlayer in Swift?

2017-01-08 Thread Charles Srstka
> On Jan 8, 2017, at 1:12 PM, Quincey Morris 
>  wrote:
> 
> On Jan 8, 2017, at 05:49 , Charles Jenkins  > wrote:
>> 
>> changing to CDouble didn’t help
> 
> This is one of those cases where I regretted pressing “Send” just 2 minutes 
> later. What I wrote was a thought process that didn’t make complete sense.
> 
> There are 4 possibilities and you’ll need to narrow it down to one:
> 
> 1. The property type is incorrect. You could try changing it to an explicit 
> NSNumber, which is the type that the binding actually requires.

This is not the problem; KVO works just fine with a property typed as Double as 
long as the property is marked ‘dynamic', which my sample code demonstrates 
(for some reason, the mailing list software separated the “.zip” from the rest 
of the link, so just add “.zip” to the end manually to download it).

> 2. The property accessors are not using the correct calling convention 
> (@objc). If they’re in a view controller subclass (which is an @objc) object, 
> they’ll normally be @objc, but there are some situations (e.g. declaring them 
> private) that may make them native Swift. Leaving off the “dynamic” would 
> come under this case too, but this was covered already.
> 
> 3. The property declaration is fine, but IB is broken and doesn’t recognize 
> the property as compatible. It may simply fail to set up the binding 
> properly, even though it would work if it did. You could try leaving it 
> unbound, and set up the binding at run time.
> 
> 4. The property is fine, and something else is wrong.
> 
> Finally, I’d note that the discussion in this thread had jumped back and 
> forth between bindings and KVO. I’ve lost track of whether you’re saying that 
> KVO isn’t working here (Charles posted sample code that he said works), or 
> whether bindings aren’t working here.


I think that seeing a simplified version of the code that isn’t working would 
be the easiest way to debug this at this point. OP, would you mind posting it?

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: AVSimplePlayer in Swift?

2017-01-07 Thread Charles Srstka
> On Jan 7, 2017, at 3:24 PM, Charles Jenkins  wrote:
> 
> I did try after you asked, and KVO may be working, but the video doesn’t 
> play. If I delete the KVO bindings from IB and change my code like this:
> 
>   var currentTime : Double = 0 {
> didSet {
>   timeSlider.doubleValue = currentTime
> }
>   }
> 
>   var duration: Double = 0
>   {
> didSet {
>   timeSlider.maxValue = duration
> }
>   }
> 
> The video will play and all the buttons will work right. Seriously, 
> *everything* works except I can’t scrub and I haven’t bothered yet to test 
> the volume slider.
> 
> If I take that working code and the ONLY changes I make are to (a) change 
> currentTime to the code below and (b) add the binding in IB, the video will 
> not play. The strange thing is when I do this, I think KVO is actually 
> working because I get hammered with log messages saying “Seek to 0.0 seconds.”
> 
>   dynamic var currentTime : Double {
> get {
>   return CMTimeGetSeconds( player.currentTime() )
> }
> set ( seconds ) {
>   NSLog( "Seek to \(seconds) seconds" )
>   let time = CMTimeMakeWithSeconds( seconds, 1 )
>   player.seek( to: time )
> }
>   }
> 
> I thought maybe this meant my periodic time observer was messed up, so I 
> replaced my equivalent of the ObjC code with this:
> 
>   myTimeObserver = player.addPeriodicTimeObserver(
> forInterval: CMTimeMake( 1, 10 ),
> queue: DispatchQueue.main
>   ) {
> [weak self] ( time: CMTime ) -> () in
> if let weakSelf = self {
>   let seconds = weakSelf.currentTime // Force a read from player
>   NSLog( "Asking to set time to \(seconds) seconds" )
>   weakSelf.currentTime = seconds // Force KVO update
> }
>   }
> 
> And the resulting log messages prove, I think, that player.currentTime() 
> really does sit at 0.0 while I’m using KVO for the slider.

That’s odd that the currentTime variable would stay at 0.0. Have you checked 
“Continuous” for your slider in IB?

If it helps, I made a simple example project connecting a slider and Swift via 
KVO. You can drag the slider around and watch the image update as you do:

http://www.charlessoft.com/extraneous_stuff/Slider_Test 
.zip

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: AVSimplePlayer in Swift?

2017-01-06 Thread Charles Srstka
> On Jan 6, 2017, at 9:32 PM, Charles Jenkins  wrote:
> 
>   - If I imitate the ObjC version and try to do the bindings in IB, the
>   time slider’s maxValue and value bindings don’t work (won’t compile)
>   because duration and currentTime are not NSNumbers.

They don’t have to be NSNumbers; KVO automatically wraps primitive number types 
in NSNumbers for you. What do you mean by “won’t compile”? IB and KVO all occur 
at runtime, not compile-time.

Anyway, the thing to make sure about is that you’ve declared all KVO-compliant 
properties with the ‘dynamic’ keyword. If you haven’t, that could easily 
account for things not working properly.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: What should we do if file-opening takes a long time?

2016-12-31 Thread Charles Srstka
> On Dec 31, 2016, at 7:35 PM, Graham Cox  wrote:
> 
> NSProgress is thread safe and might be useful for this.

One thing to be careful about when using NSProgress with threads is not to bind 
directly to it from your UI elements, since the updates will come in on the 
same thread the changes were made on. Either register your observers manually 
and call the main thread from 
-observeValue:forKeyPath:ofObject:change:context:, or have your worker thread 
call the main thread to update the NSProgress object.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com


Re: What should we do if file-opening takes a long time?

2016-12-31 Thread Charles Srstka
> On Dec 31, 2016, at 1:06 PM, Jens Alfke  wrote:
> 
>> On Dec 31, 2016, at 12:52 AM, Daryle Walker > > wrote:
>> 
>> Let’s assume we’re using a NSDocument-based application.  If we’re opening a 
>> big file, like a gigabyte or more, does the system code automatically show a 
>> progress bar dialog?  Or does the user look at a whole bunch of nothing 
>> (i.e. wondering if the app locked up)?
> 
> If I had an app that took a long time to read a document, I’d make the actual 
> reading asynchronous, so the app would be responsive and open the window 
> quickly, even if the window’s content just showed as a progress bar.

What I do is to open the window right away, then open a sheet on it with a 
progress bar until the loading is finished.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: Elementary NSUserDefaults Question

2016-12-07 Thread Charles Srstka
> On Dec 7, 2016, at 1:00 PM, Quincey Morris 
>  wrote:
> 
> On Dec 7, 2016, at 08:24 , Charles Jenkins  > wrote:
>> 
>> If anyone knows how to play music from the library at a low volume, without
>> screwing up the system volume for other apps, e.g. Music.app, I’d love to
>> learn it.
> 
> 
> You can play audio using any volume you want (without any side effects on the 
> system volume level) via an AVAudioPlayer. 
> 
> A couple of points about the “nil” thing, given that you’re writing in Swift:
> 
> 1. Swift always had a conceptual ambiguity between a nil-valued optional 
> meaning the absence of a value and meaning the presence of a value of 
> Optional type (a 2-valued enum with an associated value on the non-optional 
> case). However, the compiler treated type Optional specially, so that it 
> generally did what you want, even if the semantics were sometimes obscure in 
> edge cases.
> 
> 2. Swift 3 “improved” the situation by regularizing the behavior for the edge 
> cases, but the side effect was that the semantics of "absent value" vs. 
> "present non-value" have drifted apart a tiny bit. That makes optionals 
> slightly less intuitive to use.
> 
> For example, in Swift 3, it’s feasible to allow “nil values” in a dictionary. 
> If you have a dictionary whose values are optional strings (say, [String: 
> String?], to be concrete), and you look up a key that has a value, you get a 
> result of type String?, which may or may not be nil. If you look up a key 
> that has no value, you get a result of “nil as String??”, with two levels of 
> optionality.
> 
> That’s confusing but not ambiguous. The trouble is that now we have *two* 
> kinds of presence (concrete values) representing *different* kinds of 
> absence. This is a slippery slope, and I regard it as one indigestible defect 
> in Swift 3.

With all that said, when I pass nil to UserDefaults’ set(forKey:) method in 
Swift 3, instead of deleting the entry like I remember it doing in the past, it 
ends up writing an NSNull instead of deleting the key (well, actually, it 
encodes an NSNull using NSKeyedEncoder and then stores that as an NSData, but 
still). I think this is because of SE-0140 
(https://github.com/apple/swift-evolution/blob/master/proposals/0140-bridge-optional-to-nsnull.md
 
),
 since the method on UserDefaults takes an Any?, and Swift now sends NSNulls to 
Objective-C methods that do. So, if OP upgrades to Swift 3, he may find that it 
suddenly does what he wants, albeit accidentally. I’m not sure I’d want to rely 
on this behavior, though.

Charles
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Why aren't NSFilePromiseProviderDelegate methods being called?

2016-12-06 Thread Charles Srstka
Okay, so I decided to try to experiment with NSFilePromiseProvider, in order to 
replace some legacy code using old-fashioned drag-and-drop methods. However, 
for some reason, the drag-and-drop system seems to completely ignore my 
NSFilePromiseProviderDelegate methods, and calls the old-fashioned ones 
instead. If they’re not there, it throws an exception. What the heck?

Here’s the code:

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet var outlineView: NSOutlineView?

class Item: NSObject {
@objc let name: String
@objc let children: [Item]

init(name: String, children: [Item] = []) {
self.name = name
self.children = children
super.init()
}
}

@IBOutlet weak var window: NSWindow!

dynamic var items = [Item(name: "Foo"), Item(name: "Bar"), Item(name: 
"Baz", children: [Item(name: "Qux")])]

func applicationDidFinishLaunching(_ aNotification: Notification) {
self.outlineView?.setDraggingSourceOperationMask(.copy, forLocal: false)
}
}

extension AppDelegate: NSOutlineViewDataSource {
func outlineView(_ outlineView: NSOutlineView, pasteboardWriterForItem 
item: Any) -> NSPasteboardWriting? {
return NSFilePromiseProvider(fileType: kUTTypePlainText as String, 
delegate: self)
}

// If this method doesn't exist, an exception is thrown on drag
func outlineView(_ outlineView: NSOutlineView, 
namesOfPromisedFilesDroppedAtDestination dropDestination: URL, forDraggedItems 
items: [Any]) -> [String] {
print("Why does this get called instead of my 
NSFilePromiseProviderDelegate methods?!")

try! "foo".write(to: dropDestination.appendingPathComponent("foo.txt"), 
atomically: true, encoding: .utf8)
return ["foo.txt"]
}
}

extension AppDelegate: NSFilePromiseProviderDelegate {
func filePromiseProvider(_ filePromiseProvider: NSFilePromiseProvider, 
fileNameForType fileType: String) -> String {
print("fileNameForType: got called with type \(fileType)")
return "foo.txt"
}

func filePromiseProvider(_ filePromiseProvider: NSFilePromiseProvider, 
writePromiseTo url: URL, completionHandler: @escaping (Error?) -> Void) {
print("writePromiseTo: got called with URL \(url)")
do {
try "foo".write(to: url, atomically: true, encoding: .utf8)
completionHandler(nil)
} catch {
completionHandler(error)
}
}
}

Output is:

Why does this get called instead of my NSFilePromiseProviderDelegate methods?!

I mean, it works, but it works using the older system. I want it to use the 
modern system. Why won’t it?

Charles
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Why aren't NSFilePromiseProviderDelegate methods being called?

2016-12-05 Thread Charles Srstka
Okay, so I decided to try to experiment with NSFilePromiseProvider, in order to 
replace some legacy code using old-fashioned drag-and-drop methods. Seems 
simple enough; just have the outline view delegate’s 
-outlineView:pasteboardWriterForItem: method return an NSFilePromiseProvider. 
However, for some reason, when I drag something from the outline view to the 
Finder, the drag-and-drop system seems to completely ignore my 
NSFilePromiseProviderDelegate methods, and calls the old-fashioned 
-outlineView:namesOfPromisedFilesDroppedAtDestination:forDraggedItems: method 
instead. If it's not there, it throws an exception. What the heck?

Project is at: http://www.charlessoft.com/FilePromisesTest.zip

I mean, it works, but it works using the older system. I want it to use the 
modern system. Why won’t it?

Charles
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: Preserving knowledge of renamed/moved directory?

2016-11-28 Thread Charles Srstka
> On Nov 28, 2016, at 7:42 PM, Quincey Morris 
> <quinceymor...@rivergatesoftware.com> wrote:
> 
> On Nov 28, 2016, at 17:30 , Charles Srstka <cocoa...@charlessoft.com 
> <mailto:cocoa...@charlessoft.com>> wrote:
>> 
>> This is currently broken in Swift, as of Swift 3, where all file reference 
>> URLs will get silently and unceremoniously converted back to path-based ones 
>> at the bridge.
> 
> NSURL or URL or both?

.fileReferenceURL doesn’t exist on URL. It does exist on NSURL, but thanks to 
the bridging magic it returns a URL, which the ObjC-Swift bridge turns into a 
normal file path URL.

Unfortunately, the second comment on this thread: 
https://bugs.swift.org/browse/SR-2728 <https://bugs.swift.org/browse/SR-2728> 
indicates that this might have been intentional behavior. :-/

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: Preserving knowledge of renamed/moved directory?

2016-11-28 Thread Charles Srstka
> On Nov 28, 2016, at 7:06 PM, Rick Mann  wrote:
> 
> Back in the days before URLs, I could have an FSRef to a directory, and no 
> matter where I moved that directory what I named it, the FSRef was still 
> valid, and I could still read/write to it.
> 
> Now that everything is URL based, if a thread changes the name of a 
> directory, or moves it, another thread's URL pointing to that directory (or 
> inside it) becomes invalid, right?
> 
> Is there any way for this to not be the case? That is, for a URL to a 
> directory or subdirectory or item within to stay valid even if the path to it 
> changes?

I’ve got good news and bad news.

The good news: Yes, there is a way. Just call .fileReferenceURL on an NSURL in 
Objective-C, and you’ll get something that works just like an FSRef.

The bad news: This is currently broken in Swift, as of Swift 3, where all file 
reference URLs will get silently and unceremoniously converted back to 
path-based ones at the bridge. This can be worked around via an Objective-C 
wrapper, though.

Charles


___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: How to ResolvingSymlinksInPath ?

2016-11-04 Thread Charles Srstka
> On Nov 3, 2016, at 10:39 PM, Ken Thomases  wrote:
> 
> On Nov 3, 2016, at 10:08 PM, Gerriet M. Denkmann  > wrote:
>> 
>> URLByResolvingAliasFileAtURL does almost the same, has no special behaviour 
>> with “/private”, and even can resolve an alias.
>> But: only when this alias is the final component of a path.
>> I.e. /path/aliasToFoo will be resolved to /path/foo; but  
>> /path/aliasToFoo/someFile will not.
> 
> Paths "through" alias files make no sense.  Nothing else in the system will 
> resolve an alias there, so nothing will ever produce such a path.  If your 
> code is producing such paths, you should fix it, because nothing else will be 
> able to process them.

Oh, and it isn’t quite true that *nothing* else on the system will be able to 
process paths through an alias; old-style HFS paths separated by the ‘:’ 
character do resolve through aliases if they go through the old-style Carbon 
file manager. You can test this yourself by writing an AppleScript like this:

tell application "Finder"
get file “Macintosh HD:path:to:someAlias:someFile.txt"
end tell

Replace ‘Macintosh HD’ with your boot disk’s name, and the rest by the 
appropriate filenames, and you should get a valid reference to the file.

Charles
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: How to ResolvingSymlinksInPath ?

2016-11-04 Thread Charles Srstka
> On Nov 3, 2016, at 10:39 PM, Ken Thomases  wrote:
> 
> On Nov 3, 2016, at 10:08 PM, Gerriet M. Denkmann  > wrote:
>> 
>> URLByResolvingAliasFileAtURL does almost the same, has no special behaviour 
>> with “/private”, and even can resolve an alias.
>> But: only when this alias is the final component of a path.
>> I.e. /path/aliasToFoo will be resolved to /path/foo; but  
>> /path/aliasToFoo/someFile will not.
> 
> Paths "through" alias files make no sense.  Nothing else in the system will 
> resolve an alias there, so nothing will ever produce such a path.  If your 
> code is producing such paths, you should fix it, because nothing else will be 
> able to process them.
> 
>>> On 3 Nov 2016, at 23:05, Jens Alfke >> > wrote:
>>> 
>>> (I’m not sure why you need to remove all symlinks, but I’ll assume you have 
>>> a good reason…)
>> 
>> I don’t know whether the reason is good, but I want to compare stuff 
>> returned from FSEventStreams.
> 
> You should construct NSURL objects from the two paths, use 
> -getResourceValue:forKey:error: with the key NSURLFileResourceIdentifierKey 
> to get the resource ID for each, and then use [resourceID1 
> isEqual:resourceID2] to determine if the two paths refer to the same 
> file-system object.

One thing that may be worth mentioning is that file resource identifier keys 
apparently use the inode to compare the files, which means that comparing the 
file resource identifiers of two hard links that point to the same inode will 
return true. This is great if that’s what you want, but if you need to 
determine that they represent the same catalog node rather than the same 
underlying data, it may not be appropriate.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: EXC_BAD_INSTRUCTION when enumerating /.DocumentRevisions-V100/

2016-10-22 Thread Charles Srstka
> On Oct 22, 2016, at 2:42 PM, Jean Suisse  wrote:
> 
>> 
>> On 22 Oct 2016, at 21:24, Quincey Morris 
>> > > wrote:
>> 
>> On Oct 22, 2016, at 11:42 , Jean Suisse >  > >> wrote:
>>> 
>>> My app should get an access denied error (the enumerator should be nil for 
>>> instance). It shouldn’t crash.
>> 
>> It can’t return nil, because that is used to signal the end of the 
>> enumeration. I agree it’s nasty if it crashes, though.
> 
> I am not talking about enumerator?.nextObject() but about 
> manager.enumerator(at: includingPropertiesForKeys: options:), which in the 
> API return an optional FileManager.DirectoryEnumerator?, which I expect to be 
> nil when there is nothing to enumerate. 
> 
> However, the doc states:
> 
>   Returns: An NSDirectoryEnumerator object that enumerates the contents 
> of the directory at url. If url is a filename, the method returns an 
> enumerator object that enumerates no files—the first call to 
> nextObject()returns nil.
> 
> So, why make it an optional value at all?
> 
>> 
>>> Though it looks like I am trying to access "/.DocumentRevisions-V100/“, it 
>>> is not what I am trying to achieve. 
>>> 
>>> At some point my app needs to enumerate user-selected directories. The 
>>> issue is I get a crash when directories such as "/.DocumentRevisions-V100/“ 
>>> are present.
>>> I cannon reasonably maintain a list of “don’t enumerate” directories.
>> 
>> It’s still not quite clear what your real code is trying to do. If you were 
>> enumerating the *root* directory *shallowly* 
>> (.skipsSubdirectoryDescendants), and you hit this directory, you should 
>> *not* try to descend explicitly into this directory (or any directory whose 
>> name begins with a period, I suppose) as your sample code does. If you were 
>> doing a deep enumeration from the root directory, you wouldn’t be executing 
>> shallow enumeration code as in your sample code.
> 
> Yes, I enumerate shallowly. Yes I hit the directory. And yes, the user may 
> take an action that will lead my app to try enumerating directories such as 
> "/.DocumentRevisions-V100/“ shallowly.
> The finder doesn’t crash when I try to open .DocumentRevisions-V100. Neither 
> should my app.
> 
>> Can you use the .skipsHiddenFiles option for your real enumerator? That will 
>> skip files and directories whose name starts with a period.
> 
> I could. But I still may hit directories that the user does not have the 
> permission to access. .DocumentRevisions-V100 is really just for the example.
> 
>> 
>>> To refine, what difference is there between ObjC’s 
>>> for (NSURL* file in enumerator)
>>> 
>>> and swift’s
>>> 
>>> while let file = enumerator?.nextObject() as? URL
>>> ?
>> 
>> You’re comparing unlike things. Regardless of language, “for … in” and 
>> “while … nextObject” use different mechanisms for maintaining state between 
>> iterations. What does the Swift version of the “for … in” loop do?
> 
> Jens asked if an equivalent in ObjC would crash. That’s what I came up with. 
> The for … in loop performs gathers data about the file and folders, puts them 
> in an array, returns it to the caller function, then the app continues 
> interacting with the user.

I just tried it myself, and indeed got your crash. The backtrace is:

* thread #1: tid = 0x3f24f, 0x0001000ca265 foo`static 
Foundation.DateComponents._unconditionallyBridgeFromObjectiveC 
(Swift.Optional<__ObjC.NSDateComponents>) -> Foundation.DateComponents with 
unmangled suffix "_merged" + 85, queue = 'com.apple.main-thread', stop reason = 
EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
frame #0: 0x0001000ca265 foo`static 
Foundation.DateComponents._unconditionallyBridgeFromObjectiveC 
(Swift.Optional<__ObjC.NSDateComponents>) -> Foundation.DateComponents with 
unmangled suffix "_merged" + 85
frame #1: 0x0001204b foo`thunk + 59 at main.swift:0
frame #2: 0x7fff78be6c82 Foundation`-[NSURLDirectoryEnumerator 
nextObject] + 101
  * frame #3: 0x00011888 foo`main + 952 at main.swift:17
frame #4: 0x7fff8c1d5255 libdyld.dylib`start + 1

It looks like we’ve got a bridging issue here; my guess is that Objective-C is 
presenting nil to something that Swift didn’t expect to be optional. It’s 
pretty obviously a bug; I’d file a Radar on it.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: Stupid objective-c question

2016-09-22 Thread Charles Srstka
> On Sep 22, 2016, at 6:07 PM, Quincey Morris 
>  wrote:
> 
> But that’s because the KVO notification mechanism is a more ancient design 
> concept, where it likely seemed simple, adequate and flexible. I assume it 
> comes from NeXTStep days (late 80s or early 90s), not OS X 10.0 days (early 
> 2000s), although I don’t know for sure.

Actually nope, it showed up in 10.3, making it younger than the target/selector 
approach.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: How to Launch an App using the Bundle ID?

2016-09-20 Thread Charles Srstka
> On Sep 20, 2016, at 5:48 AM, Dave  wrote:
> 
> Hi All,
> 
> 
> I’m using launchApplication method from Shared Workspace, however, it accept 
> an Application Name and all I have is the Bundle ID. How can I launch an App 
> using the Bundle ID?
> 
> All the Best
> Dave

Get the URL of the application by using -[NSWorkspace 
URLForApplicationWithBundleIdentifier:], then launch the application by the URL.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: loadNibNamed deprecated, but newer version crashes

2016-09-18 Thread Charles Srstka
What’s the crash? Is it an exception? If so, what’s the description that gets 
posted to the console?

Charles

> On Sep 18, 2016, at 6:35 PM, Gabriel Zachmann  wrote:
> 
> I would like to replace this line of code:
>   [NSBundle loadNibNamed: @"ConfigureSheet" owner: self];
> 
> by the newer version loadNibNamed: owner:topLevelObjects:.
> 
> This runs in a screensaver. The deprecated version (loadNibNamed:owner:) 
> works.
> The new version causes a crash.
> Here are the variants I have tried:
> 
> 1.
> 
> NSBundle * bundle = [NSBundle bundleForClass:[self class]];
> NSArray * nibArray = nil;
> [bundle loadNibNamed: @"ConfigureSheet" owner: self topLevelObjects: 
> ];
> 
> 2.
> 
> NSBundle * bundle = [NSBundle bundleForClass:[self class]];
> [bundle loadNibNamed: @"ConfigureSheet" owner: self topLevelObjects: nil;
> 
> 3.
> 
> [[NSBundle mainBundle] loadNibNamed: @"ConfigureSheet" owner: self 
> topLevelObjects: nil];
> 
> 
> 
> I must be missing something.
> 
> I have checked the API docs, but I didn't see any hints. I have googled 
> extensively, to no avail.
> 
> Any hints, pointers, suggestions will be highly appreciated.
> 
> Best regards, 
> Gabriel.
> 
> 
> ___
> 
> Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)
> 
> Please do not post admin requests or moderator comments to the list.
> Contact the moderators at cocoa-dev-admins(at)lists.apple.com
> 
> Help/Unsubscribe/Update your Subscription:
> https://lists.apple.com/mailman/options/cocoa-dev/cocoadev%40charlessoft.com
> 
> This email sent to cocoa...@charlessoft.com


___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: referencing a Swift Dictionary from Objective-C

2016-09-10 Thread Charles Srstka
> On Sep 11, 2016, at 12:16 AM, Gavin Eadie  wrote:
> 
> I’m moving some code from Obj-C to Swift and, from time to time, I open a gap 
> I cannot see across.  This is one, and I’d love some assistance.
> 
> I converted a pile of utility Obj-C code that included a class method of the 
> form on the rhs of:
> 
>   xxx = [UIColor colorFromName:@"aliceblue"]
> 
> In the new Swift replacement of the utility code, I added a global constant 
> Dictionary of the form:
> 
>   public let colorLookup = [
>  "aliceblue" : UIColor.init(colorLiteralRed:0.0, green:0.5, blue:1.0, 
> alpha:1.0),
>  …
>   ]
> 
> and changed the Obj-C call to
> 
>   xxx = colorLookup[@"aliceblue"]
> 
> 
> The Obj-C compiler complains that the subscript is not numeric.  It also 
> appears to not be able to resolve the global constant "colorLookup" (which 
> probably explains the error in the previous sentence).  I notice that 
> "colorLookup" doesn’t appear in "Utilities-Swift.h" ..
> 
> There are other (and better) ways I could code this, but I’m curious why 
> "colorLookup" is invisible to Objective-C .. Thanks, Gavin

Wrap the variable in an Objective-C class and it should be fine:

public class Constants: NSObject {
public let colorLookup: [String : UIColor] = ...
}

Charles
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: array = [NSArray new] or array = [NSArray array]?

2016-08-19 Thread Charles Srstka
> On Aug 19, 2016, at 9:56 PM, Charles Srstka <cocoa...@charlessoft.com> wrote:
> 
>>> So for the foreseeable future, the
>>> difference is that +array returns an autoreleased object, meaning that in
>>> ARC code, +new is the better choice.
>> 
>> I would not make that assumption. Who says +[NSArray array] constructs
>> anything at all? Try comparing the return values of two calls to
>> [NSArray array] sometime. ;-)
>> 
>> I happen think +new is more readable, but it’s really just a matter of
>> preference.
> 
> Just because you didn’t create a brand-new object doesn’t mean you can’t (or 
> that you shouldn’t, under pre-ARC coding conventions) do a retain-autorelease 
> dance on it.

As an aside:

#import 
#include 

void SetUpVeryVeryBadAutoreleaseHack() {
Class class = [[NSArray array] class]; // because it won't just be 
NSArray due to the class cluster
SEL selector = NSSelectorFromString(@"autorelease");

Method method = class_getInstanceMethod(class, selector);
IMP oldImpl = method_getImplementation(method);

IMP newImpl = imp_implementationWithBlock(^id(id s) {
NSLog(@"NSArray %p's -autorelease called", s);

return ((id (*)(id, SEL)) oldImpl)(s, selector);
});

method_setImplementation(method, newImpl);
}

int main(int argc, char *argv[]) {
@autoreleasepool {
// Just in case one of you complains ;-)
NSLog(@"Do +[NSArray array] and +[NSArray new] return the same 
class: %u", [[NSArray array] class] == [[NSArray new] class]);

SetUpVeryVeryBadAutoreleaseHack();

NSLog(@"calling +[NSArray array]");
NSArray *arr1 = [NSArray array];
NSLog(@"calling +[NSArray new]");
NSArray *arr2 = [NSArray new];
}
}

returns:

2016-08-19 22:03:42.599 Untitled[14693:2298098] Do +[NSArray array] and 
+[NSArray new] return the same class: 1
2016-08-19 22:03:42.600 Untitled[14693:2298098] calling +[NSArray array]
2016-08-19 22:03:42.600 Untitled[14693:2298098] NSArray 0x7fbdf2400180's 
-autorelease called
2016-08-19 22:03:42.600 Untitled[14693:2298098] calling +[NSArray new]

Could this change in the future? Theoretically, but it’s unlikely, since 1) 
it’s entirely possible that doing so could break binary compatibility, causing 
crashes if any app accessed the array at a time where it would have been 
deallocated had it not been in the autoreleasepool, and 2) there’d be very 
little benefit to doing so, since eventually we’re going to get to a point 
where most new code is in Swift, which won’t access either of these 
initializers.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: array = [NSArray new] or array = [NSArray array]?

2016-08-19 Thread Charles Srstka
> On Aug 19, 2016, at 8:25 PM, Kyle Sluder <k...@ksluder.com> wrote:
> 
> 
> 
> On Fri, Aug 19, 2016, at 06:08 PM, Charles Srstka wrote:
>>> On Aug 19, 2016, at 3:46 PM, Quincey Morris 
>>> <quinceymor...@rivergatesoftware.com> wrote:
>>> 
>>> On Aug 19, 2016, at 10:53 , Charles Srstka <cocoa...@charlessoft.com 
>>> <mailto:cocoa...@charlessoft.com>> wrote:
>>>> 
>>>> [NSArray array] is a synonym for [[[NSArray alloc] init] autorelease].
>>> 
>>> (along with other similar comments in other responses)
>>> 
>>> To be pedantic, it’s *implemented* as [[[NSArray alloc] init] autorelease], 
>>> but the lack of an API contract to that effect means that “synonym” isn’t 
>>> quite accurate.
>>> 
>>> My point is that Apple might revisit the implementation of NSArray at any 
>>> time (in these Swiftian days, stranger things have happened), and choose to 
>>> write it with full ARC compatibility, which means there might not be any 
>>> autorelease when invoked from ARC client code, since ARC can optimize the 
>>> code when it handles both ends of the invocation.
>> 
>> Swift typically just calls the initializer if it’s there, so the
>> convenience initializers like +[NSArray array] are really only relevant
>> to Objective-C code. For that reason, I doubt they’d change unless Apple
>> did something crazy like rewrite the entire frameworks in Swift, in which
>> case they’d probably go away.
> 
> There is an official reimplementation of Foundation/CoreFoundation in
> Swift. The implementation of NSObject lacks a `static func new`:
> <https://github.com/apple/swift-corelibs-foundation/blob/master/Foundation/NSObject.swift>
> Likewise, Swift explicitly does not bridge `+new` from ObjC, so this is
> a moot point in Swift code.

When dealing with an Objective-C object ‘Foo', Swift’s initializer Foo() calls 
[[Foo alloc] init] under the hood, which is the same thing +new does, so +new 
is of course not necessary in Swift and is not imported (just like +[NSArray 
array]).

>> So for the foreseeable future, the
>> difference is that +array returns an autoreleased object, meaning that in
>> ARC code, +new is the better choice.
> 
> I would not make that assumption. Who says +[NSArray array] constructs
> anything at all? Try comparing the return values of two calls to
> [NSArray array] sometime. ;-)
> 
> I happen think +new is more readable, but it’s really just a matter of
> preference.

Just because you didn’t create a brand-new object doesn’t mean you can’t (or 
that you shouldn’t, under pre-ARC coding conventions) do a retain-autorelease 
dance on it.

Charles


___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: array = [NSArray new] or array = [NSArray array]?

2016-08-19 Thread Charles Srstka
> On Aug 19, 2016, at 3:46 PM, Quincey Morris 
> <quinceymor...@rivergatesoftware.com> wrote:
> 
> On Aug 19, 2016, at 10:53 , Charles Srstka <cocoa...@charlessoft.com 
> <mailto:cocoa...@charlessoft.com>> wrote:
>> 
>> [NSArray array] is a synonym for [[[NSArray alloc] init] autorelease].
> 
> (along with other similar comments in other responses)
> 
> To be pedantic, it’s *implemented* as [[[NSArray alloc] init] autorelease], 
> but the lack of an API contract to that effect means that “synonym” isn’t 
> quite accurate.
> 
> My point is that Apple might revisit the implementation of NSArray at any 
> time (in these Swiftian days, stranger things have happened), and choose to 
> write it with full ARC compatibility, which means there might not be any 
> autorelease when invoked from ARC client code, since ARC can optimize the 
> code when it handles both ends of the invocation.

Swift typically just calls the initializer if it’s there, so the convenience 
initializers like +[NSArray array] are really only relevant to Objective-C 
code. For that reason, I doubt they’d change unless Apple did something crazy 
like rewrite the entire frameworks in Swift, in which case they’d probably go 
away. So for the foreseeable future, the difference is that +array returns an 
autoreleased object, meaning that in ARC code, +new is the better choice.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: Resend: array = [NSArray new] or array = [NSArray array]?

2016-08-19 Thread Charles Srstka
> On Aug 16, 2016, at 9:42 AM, Alex Zavatone  wrote:
> 
> I sent this out this morning but it got eaten, so this is a resend.  Sorry if 
> it gets to some of you twice.
> 
> 
> 
> Yes, I know about literals, but I have a different question here.
> 
> 
> Is this safe?
> 
> I have seen this in some code in our codebase:
> array = [NSArray new]; 
> 
> I'm familiar with using the public method from the NSArray header and what 
> the docs say to use:
> or array = [NSArray array];
> 
> Is there any risk to using [NSArray new] to init an array instead of [NSArray 
> array]??
> 
> I'm surprised to see this being used in our codebase and would like to make 
> sure we are not destroying the universe by using it.

They’re both perfectly fine. [NSArray new] is just a synonym for [[NSArray 
alloc] init], whereas [NSArray array] is a synonym for [[[NSArray alloc] init] 
autorelease].

In ARC, I actually prefer +new, as there’s no difference UI-wise, and it keeps 
the array out of the autorelease pool.

Charles


___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: NSTask Open Word File

2016-08-11 Thread Charles Srstka
> On Aug 11, 2016, at 5:20 PM, Gurkan Erdogdu  wrote:
> 
> Hi folks
> In my Swift application, I try to open a Word file with Microsoft Word 
> application via NSTask. Here is the code:
> let task = NSTask()
> task.launchPath = bundle!.executablePath
> task.arguments = ["file.docx"]
> task.launch()
> task.waitUntilExit()
> 
> But when word is launched, it popsup Grant Access dialog box. How can I 
> dismiss this dialog box and open the file directly?
> BestGurkan

Don’t use NSTask for that. Use -[NSWorkspace 
openURLs:withAppBundleIdentifier:options:additionalEventParamDescriptor:launchIdentifiers:].
 Don’t be daunted by the large number of arguments; the first two are the only 
ones you need to worry about.

Charles


___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: Root URL and URLByDeletingLastPathComponent

2016-07-17 Thread Charles Srstka
> On Jul 17, 2016, at 5:30 AM, Mike Abdullah  wrote:
> 
> It might be a mishandling of the two sorts of rot URL. If you try feeding in 
> this URL manually:
> 
> file://localhost/ 
> 
> and removing the last component, what do you end up with?

import Foundation

let url = NSURL(string: "file://localhost/")!
print(url.URLByDeletingLastPathComponent!)

outputs:

file://localhost/../

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: NSStream and Threads

2016-07-04 Thread Charles Srstka
> On Jul 4, 2016, at 1:34 AM, Gerriet M. Denkmann  wrote:
> 
> Well, seems like the main thread?

There’s your problem.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: NSStream and Threads

2016-07-03 Thread Charles Srstka
> On Jul 3, 2016, at 11:35 PM, Gerriet M. Denkmann  wrote:
> 
> When I get an NSStream I do:
> 
> aStream.delegate = myStreamDelegate;
> [ aStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode: 
> NSDefaultRunLoopMode];
> [ aStream open];
> 
> myStreamDelegate then receives stream:handleEvent: messages.
> 
> The documentation says: “The message is sent on the stream object’s thread."
> 
> Actually it is sent on the main thread.
> 
> How can I set the “stream object’s thread” ?
> 
> Gerriet.

What thread is the run loop on?

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: How to pre-select a file in NSOpenPanel -- specifically, a .app bundle?

2016-06-24 Thread Charles Srstka
> On Jun 24, 2016, at 7:47 PM, Quincey Morris 
> <quinceymor...@rivergatesoftware.com> wrote:
> 
> On Jun 24, 2016, at 16:24 , Charles Srstka <cocoa...@charlessoft.com> wrote:
>> 
>> How could this be a security threat, when a malicious program could just set 
>> canChooseDirectories to true, open the panel to the app’s parent directory, 
>> and spearphish the user into clicking OK on that?
> 
> (I wasn’t referring to opening apps, but to files generally.)
> 
> Clicking OK won’t do anything until the user selects something, and the app 
> can’t preset or change the selection. Maybe my logic is incorrect, but this 
> seems to me to prevent attempts to fool the user into choosing something 
> unintended.

func readTheFile(url: NSURL) {
do {
let data = try NSData(contentsOfURL: url, options: [])
guard let string = String(data: data, encoding: NSUTF8StringEncoding) 
else {
throw NSCocoaError.FileReadCorruptFileError
}

print("Contents of file: \(string)")
} catch {
print("Error occurred: \(error)")
}
}

let url = NSURL(fileURLWithPath: "/path/to/MyGreatFile.txt")

print("First attempt:")
readTheFile(url)

let dirURL: NSURL = {
while true {
let openPanel = NSOpenPanel()

openPanel.canChooseDirectories = true
openPanel.directoryURL = url.URLByDeletingLastPathComponent
openPanel.prompt = "OK"
openPanel.message = "Please click OK"

let answer = openPanel.runModal()

if answer == NSFileHandlingPanelOKButton, let openPanelURL = 
openPanel.URL where openPanelURL == url.URLByDeletingLastPathComponent {
return openPanelURL
} else {
let alert = NSAlert()

alert.messageText = "Hey buddy, click the OK button when I tell you 
to, okay?"

alert.runModal()
}
}
}()

print("Second attempt:")

dirURL.startAccessingSecurityScopedResource()
readTheFile(url)
dirURL.stopAccessingSecurityScopedResource()

--

After clicking OK when asked, this outputs:

First attempt:
Error occurred: Error Domain=NSCocoaErrorDomain Code=257 "The file 
“MyGreatFile.txt” couldn’t be opened because you don’t have permission to view 
it." UserInfo={NSFilePath=/path/to/MyGreatFile.txt, 
NSUnderlyingError=0x60046750 {Error Domain=NSPOSIXErrorDomain Code=1 
"Operation not permitted"}}
Second attempt:
Contents of file: This is my great file!

Charles


___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: How to pre-select a file in NSOpenPanel -- specifically, a .app bundle?

2016-06-24 Thread Charles Srstka
> On Jun 24, 2016, at 6:24 PM, Charles Srstka <cocoa...@charlessoft.com> wrote:
> 
> Making it not work with app bundles doesn’t seem to introduce any loopholes 
> that aren’t there already.

*Making it work
___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: How to pre-select a file in NSOpenPanel -- specifically, a .app bundle?

2016-06-24 Thread Charles Srstka
> On Jun 24, 2016, at 3:54 PM, Quincey Morris 
>  wrote:
> 
> 1. [Security] Being able to select an arbitrary file programmatically might 
> lead to spearphishing exploits, where the user is tricked into opening a file 
> that is otherwise inaccessible from code in the sandbox.

How could this be a security threat, when a malicious program could just set 
canChooseDirectories to true, open the panel to the app’s parent directory, and 
spearphish the user into clicking OK on that?

Making it not work with app bundles doesn’t seem to introduce any loopholes 
that aren’t there already.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: Properties: A question of style

2016-06-15 Thread Charles Srstka
> On Jun 14, 2016, at 8:42 PM, Steve Mills <sjmi...@mac.com> wrote:
> 
>> On Jun 14, 2016, at 19:45, Charles Srstka <cocoa...@charlessoft.com 
>> <mailto:cocoa...@charlessoft.com>> wrote:
>> 
>> if thisArray.empty { doSomething() }
> 
> That's not what he suggested as the 2nd form. Look again.
> 
> Steve via iPad

Except that it is. The property name, rather than the getter, is what is 
expected to be used when you’re using dot syntax (and I think when calling from 
Swift, it’s the only way to do it).

Prepending the property name with “is” is much more clear as to what you mean, 
and it’s what Apple’s recommending these days (in the Swift guidelines, but 
that’s clearly where the future is). This helps avoid confusing things like 
NSURL’s .fileURL property, which is easy to scratch your head at wondering if 
it will query whether or not the URL is a file URL or whether it will return a 
converted URL (it doesn’t help that filePathURL’s name is so similar). 
isFileURL conveys the intent perfectly.

Charles

___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: Properties: A question of style

2016-06-14 Thread Charles Srstka
> On Jun 14, 2016, at 6:48 PM, Graham Cox  wrote:
> 
> Hi all,
> 
> Just a quick point for discussion.
> 
> Suppose I have a read-only BOOL property. What’s better, to declare it as:
> 
> @property (readonly) BOOL isFoo;
> 
> or:
> 
> @property (readonly, getter=isFoo) BOOL   foo;
> 
> 
> Is there any advantage to one over the other? n.b. I’d always use the latter 
> form for read/write properties, it’s readonly ones that I’m wondering about.
> 
> —Graham

The former is what Apple’s recommending in the Swift guidelines, so it’s 
probably the more future-proof of the two.

I’ve always felt this style to read more naturally, too. 

if thisArray.isEmpty { doSomething() } // reads as “If this array is empty, do 
something."

if thisArray.empty { doSomething() } // reads as “Grok say this array empty! 
Grok do something! GRARRRGH! ::conks you on the head with a club::"

Charles


___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: NSFileWrapper

2016-06-05 Thread Charles Srstka
> On Jun 5, 2016, at 1:27 AM, Graham Cox  wrote:
> 
> 
>> On 5 Jun 2016, at 8:02 AM, Daryle Walker  wrote:
>> 
>> You have to come up with a new extension.  For instance, if you’re already 
>> using “.xyz” for you single-file format, you could use “.xyz-pkg” for your 
>> package format.
> 
> 
> You can use the same extension and leave it to your app to figure out which 
> it’s actually dealing with - the extension is only used to map the file to an 
> app that can open it - after that the file will be passed to NSDocument as a 
> NSFileWrapper whatever its contents - packagae or flat file. Your app can 
> then determine which it is based on some private knowledge about its 
> structure.
> 
> Alternatively, make up a  new extension - the amount of work for your app is 
> about the same, so the question is whether you want to disguise the change 
> for end users.
> 
> —Graham

My favorite way to deal with bundle documents is to just override 
readFromURL:ofType:error:, make an NSBundle from that, and load things lazily 
as needed.

Every time I’ve ever tried to use NSFileWrapper, I’ve always ended up having to 
switch to something else because of the memory issue that Jens mentions. Never 
really understood the point of that class.

Charles


___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: Very basic need, very difficult to achieve.

2016-05-06 Thread Charles Srstka
> On May 6, 2016, at 11:19 AM, Richard Charles <rcharles...@gmail.com> wrote:
> 
> 
>> On May 5, 2016, at 10:33 PM, Charles Srstka <cocoa...@charlessoft.com> wrote:
>> 
>>> On May 5, 2016, at 9:39 PM, Richard Charles <rcharles...@gmail.com> wrote:
>>> 
>>> 
>>>> On May 5, 2016, at 6:07 PM, Richard Charles <rcharles...@gmail.com> wrote:
>>>> 
>>>> Can you run this application?
>>>> 
>>>> “OpenGL Extensions Viewer"
>>>> 
>>>> http://www.realtech-vr.com/glview/
>>>> 
>>>> I could never get an app that uses OpenGL to work with a virtual machine.
>>> 
>>> 
>>> 
>>>> On May 5, 2016, at 8:16 PM, Charles Srstka <cocoa...@charlessoft.com> 
>>>> wrote:
>>>> 
>>>> Seems to run all right in VMWare Fusion on my machine.
>>> 
>>> 
>>> Amazing.
>>> 
>>> Click the “Tests” tab and click the “Test” button in the lower left corner.
>>> 
>>> Does it work?
>>> 
>>> --Richard Charles
>> 
>> I got an image of a rotating cube.
>> 
>> Charles
> 
> Interesting.
> 
> According to VMware Fusion 8 Documentation a Mac OS X Virtual Machine does 
> not support 3D Accelerated graphics.
> 
> http://pubs.vmware.com/fusion-8/index.jsp#com.vmware.fusion.using.doc/GUID-474FC78E-4E77-42B7-A1C6-12C2F378C5B9.html
> 
> I just called VMware technical support and they confirmed that the product 
> does not support support 3D Accelerated graphics with a Mac virtual machine.
> 
> So what is happening? Perhaps you are seeing the Apple OpenGL Software 
> Renderer being utilized by the OpenGL Extensions Viewer application. You can 
> set this with a pull down at the top of the window.
> 
> I am currently developing a Mac application that uses OpenGL but I could 
> never get it to work with Parallels. I was never able to get the application 
> to fall back to using the Apple Software Renderer when OpenGL hardware was 
> not present. Perhaps I was not doing something correctly.

It does appear to be using the software renderer. However, the cube does 
display and do its rotating thing.

Charles


___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Re: Very basic need, very difficult to achieve.

2016-05-05 Thread Charles Srstka
> On May 5, 2016, at 9:39 PM, Richard Charles <rcharles...@gmail.com> wrote:
> 
> 
>> On May 5, 2016, at 6:07 PM, Richard Charles <rcharles...@gmail.com> wrote:
>> 
>> Can you run this application?
>> 
>> “OpenGL Extensions Viewer"
>> 
>> http://www.realtech-vr.com/glview/
>> 
>> I could never get an app that uses OpenGL to work with a virtual machine.
> 
> 
> 
>> On May 5, 2016, at 8:16 PM, Charles Srstka <cocoa...@charlessoft.com> wrote:
>> 
>> Seems to run all right in VMWare Fusion on my machine.
> 
> 
> Amazing.
> 
> Click the “Tests” tab and click the “Test” button in the lower left corner.
> 
> Does it work?
> 
> --Richard Charles

I got an image of a rotating cube.

Charles


___

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

  1   2   3   4   5   6   7   8   9   >